Reputation: 11
I want to give class B
the ability to access the protected
attribute x
of class A
.
It is important to note, that I do not want to make x
either public
nor do I want to expose its contents via a getter
function.
The only classes that should have access to A->x
are A
and B
.
<?php
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();
I am looking for solutions to achieve this.
Upvotes: 1
Views: 156
Reputation: 2106
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();
Upvotes: 2
Reputation: 657
Extend class A with class B.
An alternative if you do not want to extend class A with class B is to use Reflection.
Upvotes: 1
Reputation: 4681
Members declared protected can be accessed only within the class itself and by inherited and parent classes
Upvotes: 1