简体   繁体   中英

PHP get_called_class() as variable for referencing static property

I'm trying every variation of the following to refer to a static property:

get_called_class()::$$prop

I've tried this:

${get_called_class()}::$$prop

I've tried many things, but can't seem to get it.

I know I can just do this:

$className = get_called_class();
$className::$$prop

BUT, that means an extra line of code. Surely there must be a way for the language to make this work on the same line. Anyone have a solution?

(By the way, the static property is protected, so it fails with ReflectionClass::getStaticPropertyValue.)

Without understanding any additional context here, you don't need to actually invoke get_called_class to poke at LSB-resolved static properties. Instead, use the static keyword to automagically resolve the currently called static class name.

class A {

    static $foo = 'from a';

    public static function test($property) {
        echo static::$$property, "\n";
    }

}

class B extends A { static $foo = 'from b'; }
class C extends A { static $foo = 'from c'; }

Example from the PHP interactive prompt:

php > include '/tmp/get_called_class.php';
php > A::test('foo');
from a
php > B::test('foo');
from b
php > C::test('foo');
from c
php >

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