PHP面向对象编程 - 从子访问父元素

时间:2015-10-08 16:34:27

标签: php oop

我们建议我们有以下类,以及以下代码:

class ParentClass {
    public $x;
    public $child;

    public function __construct($x) {
        $this->x=$x;
        $this->child=new ChildClass();
    }
}

class ChildClass extends ParentClass {

    public function __construct() {

    }

    public function tellX() {
        echo $this->x;
    }
}

$parent1=new ParentClass('test');
$parent2=new ParentClass('test2');
echo $parent1->child->tellX();
echo "<BR>";
echo $parent2->child->tellX();

这为我输出两个空行。是否有可能在对象( objParent )内创建新对象( objChild ),并访问 objParent的非静态属性来自 objChild

1 个答案:

答案 0 :(得分:1)

您所描述的内容是可能的,但您未能理解的是,在父构造函数中创建的子对象派生自父对象,但它是父对象的父实例而不是创建子对象的实例。

尝试此示例以便更好地理解:

class ParentClass {
    public $x;
    public $child;

    public function __construct($x) {
        $this->setX( $x );
        $this->child = new ChildClass( $x + 1 );
    }

    function setX( $x )
    {
        $this->x = $x;
    }

    public function tellX() {
        echo $this->x;
    }
}

class ChildClass extends ParentClass {

    public function __construct( $x )
    {
        $this->setX( $x );
    }
}

$parent1=new ParentClass(1);
$parent2=new ParentClass(2);
$parent1->tellX();
echo "<BR>";
$parent1->child->tellX();
echo "<BR>";
$parent2->child->tellX();
echo "<BR>";
$parent2->tellX();

请注意,父级和父级包含的子级没有相同的x值,但是子级继承了父级的tellX函数,即使它们没有自己定义它。

传统上,您将创建子类的实例,该实例从父级继承值/函数,而不是从父级创建子级的新实例。

关于PHP中父/子关系的一个重要注意事项是成员变量不会被继承。这就是为什么我在父语句中实现setX函数来伪造这种行为。