isset on static class attributes

2019-07-03 00:11发布

class A {
    public static $foo = 42;
}

$class = 'A';
$attribute = 'foo';

var_dump(isset($class::$attribute)); //gives bool(false)

How can i checkt, of this static attribute exists in this class?

2条回答
Root(大扎)
2楼-- · 2019-07-03 00:36

Use variable variables:

var_dump(isset($class::$$attribute)); // the two dollars are intentional

If you don't have PHP 5.3 yet the only accurate way is probably using the Reflection API:

$reflectionClass = new ReflectionClass($class);
$exists = $reflectionClass->hasProperty($attribute) && $reflectionClass->getProperty($attribute)->isStatic();
查看更多
放荡不羁爱自由
3楼-- · 2019-07-03 00:55

In 5.3, you can simply do

var_dump(property_exists($class, $attribute));
查看更多
登录 后发表回答