简体   繁体   中英

php class extends

I want to know is it possible to have a class that's extended have a var set and used from the base class?

eg:

class me
{
    public $hello = array();

    protected function setter($me)
    {
        $this->hello[] = $me;
    }
}

class foo extends me
{
    public function __construct()
    {
        $this->setter('foo');
    }
}

class yoo extends me
{
    public function __construct()
    {
        parent::setter('yoo');
    }
}

$me = new me();
$foo = new foo();
$yoo = new yoo();

print_r($me->hello);

the array printed is array() nothing is set.

Yes, you can do this by making $hello static :

public static $hello = array();

In doing so, you will have to drop the $this from $this->hello[] = $me; and replace it with a self , as hello will not longer be unique to the current object instance:

self::$hello[] = $me;

You were using

parent::setter('yoo');

But in parent class me, that function is not defined as static. So you cannot use :: to call un-static function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM