【问题标题】:php - extended classes carry objectsphp - 扩展类携带对象
【发布时间】:2010-11-07 19:00:55
【问题描述】:

我想早点问这个问题,但我想我匆忙问这个问题,并没有明白我在想什么......

$this 的值和对象是否被传递给扩展类?

<?php

class bar {

    public function foo( $t ) {

        $this->foo = $t;

    }

}

class foo extends bar {

    public function bar () {

        return $this->foo;  

    }

}

$b = new bar();
$b->foo('bar');
$f = new foo();
echo $f->bar();

?>

如果没有,是否还有另一个不将父类的对象传递给子类的声明(而不是扩展)?

问候,

菲尔

【问题讨论】:

    标签: php class extend


    【解决方案1】:

    您的示例将产生Undefined property: foo::$foo 错误。我认为您尝试使用的是 static 属性:

    class bar {
        protected static $foo;
        public function foo ($t) {
            static::$foo = $t;
        }
    }
    
    class foo extends bar {
        public function bar () {
            return static::$foo;  
        }
    }
    

    然后是:

    $b = new bar();
    $b->foo('bar');
    $f = new foo();
    echo $f->bar();
    

    ... 会回显bar,这看起来像是您想要实现的目标。

    【讨论】:

    猜你喜欢
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多