简体   繁体   中英

Access Static var from multiplie class inheritance (PHP)

How can I access $var from C class, i try with parent::parent::$var but this didn't work.

<?php 
class A {
    protected static $var = null;
    public function __construct(){
        self::$var = "Hello";
    }  
}

class B extends A {
    parent::__construct();
    //without using an intermediate var. e.g: $this->var1 = parent::$var; 
}

class C extends B {
    //need to access $var from here.
}

?>

由于变量是静态的,因此您可以像下面那样访问变量-

A::$var;

As long as the property isn't declared as private, then you can just use self:: . Anything other than private properties are available from anywhere in the hierarchy.

class A {
    protected static $var = null;
    public function __construct(){
        self::$var = "Hello";
    }
}

class B extends A {
}

class C extends B {
    function get() { echo self::$var; }
}

(new C)->get();

Hello

See https://eval.in/1022037

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