1

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.

4

3 回答 3

2

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();
于 2013-10-03T20:03:28.047 回答
1

Members declared protected can be accessed only within the class itself and by inherited and parent classes

于 2013-10-03T20:03:38.790 回答
1

用 B 类扩展 A 类。

如果您不想使用 B 类扩展 A 类,另一种方法是使用Reflection

于 2013-10-03T20:13:22.293 回答