从父类访问子变量?

pen*_*enu 4 php class

我该怎么做呢?

class test
{
    public static function run() {
        echo "Number is: ".$num;
    }
} 

class testchild extends test
{
    protected static $num = 5;
    public static function exec()  {
        $num = 5;
        parent::run();
    }
}
Run Code Online (Sandbox Code Playgroud)

testchild::exec(); 说未定义的变量“num”。

http://ideone.com/WM7tHk

我如何访问这个变量?

LSe*_*rni 5

您不应该这样做,因为您正在请求父级访问它可能存在或不存在的内容。

最简单的方法是$numparent内部声明。否则,你需要采取措施来保证系统的信息在那里,通过提供(例如)受保护的抽象静态吸气。

abstract class test
{
    public static function run() {
        echo "Number is: ".static::getNum();
    }
    protected abstract static function getNum();
}

class testchild extends test
{
    protected static $num;
    public static function exec()  {
        static::$num = 5;
        parent::run();
    }
    protected static function getNum() {
        return static::$num;
    }
}

class anotherchild extends test
{
    public static function exec()  {
        parent::run();
    }
    // We always return 42. Or maybe the Unix timestamp, who knows.
    protected static function getNum() {
        return 42;
    }
}


$c = new testchild();
$c->exec();
Run Code Online (Sandbox Code Playgroud)

传递几个变量

另一种不太可靠的方法是拥有一个“通信对象”并传递对它的引用。这可以通过与上面相同的方式完成,使用属性数组或(更好)已知结构的对象:

abstract class test
{
    public static function run() {
        echo "Number is: ".static::tell('num');
    }
    protected abstract static function tell($what);

    // A concrete function to initialize the known object would be nice here.
}

class testchild extends test
{
    protected static $info; // This is an array, out of laziness.
                            // It ought to be converted to an object.

    public static function exec()  {
        static::$info['num'] = 5;   // Typo here == possibly subtle bug.
        parent::run();
    }
    protected static function tell($what) {
        return static::$info[$what];  // array_key_exists would be nice here.
    }
}
Run Code Online (Sandbox Code Playgroud)

小改进

为了确保通信时每个对象都在同一块板上,您可以使用setter抽象通信对象(现在它也可以是一个数组):

    public static function exec()  {
        static::say('num', 5);
        parent::run();
    }
    protected static function say($what, $value) {
        // array_key_exists would be nice here too.
        static::$info[$what] = $value;
    }
Run Code Online (Sandbox Code Playgroud)

然后初始化会将对象的键设置为默认值,尝试设置不存在的键可能会引发异常。当然,你需要仔细规划不同的子类需要设置哪些信息,以及如何设置;这不是一个很好的做法,因为变化现在倾向于从孩子级联到父母级,然后是兄弟姐妹。