Class B
will have access to class A
protected members if class B
extends class A
.
A child class will have access to protected members of the parent class. A child class can also override the methods of the parent class.
You use inheritance(parent/child relationship) when one class extends the feature of another class. For example class square
can extend class rectangle
. Class square
will have all the properties and features of class rectangle
plus its own properties and features that make it different from a rectangle
.
You are implementing composition by passing in class A
into class B
. Composition is used one class uses another class. For example, an user
class may use a database
class.
class A
{
protected $x = 'some content';
}
class B
{
protected $a;
public function __construct(A $a)
{
$this->a = $a;
}
public function print_x()
{
print '???';
}
}
$b = new B(new A());
$b->print_x();
Recommended readings:
http://www.adobe.com/devnet/actionscript/learning/oop-concepts/inheritance.html
http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29
http://eflorenzano.com/blog/2008/05/04/inheritance-vs-composition/
If you have to use reflection then you can try this:
class A
{
protected $x = 'some content';
}
class B
{
protected $a;
public function __construct(A $a)
{
$this->a = $a;
}
public function print_x()
{
$reflect = new ReflectionClass($this->a);
$reflectionProperty = $reflect->getProperty('x');
$reflectionProperty->setAccessible(true);
print $reflectionProperty->getValue($this->a);
}
}
$b = new B(new A());
$b->print_x();