简体   繁体   中英

PHP: access static member of class from instance in local class member

I'd like do do this:

class A {
    public static $var = 'foo';
}

class B {
    private $a;

    public function __construct($a) {
        $this->a = $a;
    }

    public function f() {
        echo $this->a::$var; // <---- ERROR
        echo get_class($this->a)::$var; // <---- ERROR

        // WORKING but awful
        $a = $this->a;
        echo $a::$var;
    }
}

$b = new B(new A());
$b->f();

Note that I don't know if $a is an instance of A or another class, I just know that it has a static $var member. So, unfortunately, I can't use A::$var inside f .

Does anyone know if there is a single-expression syntax to do this, using PHP 5.3+?

You're passing an instance of A into B, but $var is a static Member of A which can only be accessed using :: like A::$var.

private function f() {
    echo A::$var;
}

EDIT: if you want to make it dependant of the instance stored in $a you could do something like:

public function f() {
    $class = get_class($this->a);
    echo $class::$var;
}

First thing I'm seeing is that you couldn't call f() as it is private.

$b->f();

Then maybe you can turn to something like this?

class B extends A{
    private $a;

    public function __construct($a) {
        $this->a = $a;
    }

    public function f() {
        echo static::$var;
    }
}

The following will work but I'd question why you'd want to do this:

class A {
    public static $var = 'foo';
}

class B {
    private $a;

    public function __construct($a) {
        $this->a = $a;
    }

    public function f() {
        if ($this->a instanceof A) {
            echo A::$var;
        }
    }
}

$b = new B(new A());
$b->f();

you don't need to do anything specifically with $this->a as $var is static to the class.

You could write a function like so:

function get_static_property($class, $property) {
    return $class::$$property;
}

I can't help but wonder why you would need this. Any reason why you can't have A implement an interface? Or use a trait? That way you can just echo $this->a->someMethodName() .

PS. returning strings is generally preferred over echoing inside methods.

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