使用父方法时,PHP parent :: $ property返回而不是self:$ property

时间:2013-09-03 12:01:54

标签: php class abstract-class parent self

我正在尝试创建一个具有属性/设置数组的抽象类,然后在子类中为该属性/数组添加其他属性。我希望在从子进程调用方法时,在抽象类中定义的方法使用子类属性/数组。我认为下面的代码应该可以工作......但它似乎仍然是从父类访问该属性。

abstract class AbstractClass {

    protected static $myProp;

    public function __construct() {
        self::$myProp = array(
            'a' => 10,
            'b' => 20
        );
    }

    protected function my_print() {
        print_r( self::$myProp );
    }

}

class ClassA extends AbstractClass {

    protected static $myProp;

    public function __construct() {
        parent::__construct();
        self::$myProp = array_merge( parent::$myProp, 
            array(
                'c' => 30,
                'd' => 40
            )
        );
        $this->my_print( self::$myProp );
    }

}

$myObj = new ClassA;

这应该返回数组([a] => 10 [b] => 20 [c] => 30 [d] => 40) 相反,它返回Array([a] => 10 [b] => 20)

如何让它发挥作用?!?

2 个答案:

答案 0 :(得分:2)

像这样:

<?php

abstract class AbstractClass {

    protected static $myProp;

    public function __construct() {
        self::$myProp = array(
            'a' => 10,
            'b' => 20
        );
    }

    protected function my_print() {
        print_r( self::$myProp );
    }

}

class ClassA extends AbstractClass {

    public function __construct() {
        parent::__construct();
        self::$myProp = array_merge( parent::$myProp, 
            array(
                'c' => 30,
                'd' => 40
            )
        );
        $this->my_print( self::$myProp );
    }

}

$myObj = new ClassA;

您正在覆盖变量

答案 1 :(得分:1)

实际上在父类中,您没有定义方法my_print()来包含任何参数,此外,该方法使用self::$myProp(不是static::)。 此外,由于Ka_lin已经回答,您不需要重新声明已在父类中声明的属性。

如果你这样做(由于某种原因需要重新设置它,就像设置预设值不同于父级),你可以做两件事:
例如,您可以将my_print()更改为接受参数,然后更改print_r()参数而不是self::$myProp

protected function my_print($debug) {
     print_r($debug);
}

或者,(在PHP 5.3.0版本的PHP中),您可以使用static::代替self::

protected function my_print() {
     print_r(static::$myProp);
}

我会选择第二种选择 你还应该在php手册

中准备更多关于self vs static (late binding)的内容