isset on static class attributes
Asked Answered
P

2

3
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?

Podite answered 24/4, 2011 at 16:37 Comment(2)
Please stop writing tags in question titles.Catricecatrina
@Tomala Geret'kal: ok, next time i'll do it right :)Podite
D
7

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();
Dnieper answered 24/4, 2011 at 16:39 Comment(10)
Thanks, that works :) I accept you answer as soon as I can (12 minutes left) :)Podite
Wow, variable variables can get confusing quick.Foggy
@JohnP: Probably you are using an older PHP version. The $class:: syntax was introduced in PHP 5.3.Dnieper
@nikic: How can i do this for PHP < 5.3? I want have as much compability to older versions as possible.Podite
@nikic ahhh, that's it. I haven't migrated to 5.3 yet. Was just about to -1 you after running it on codepad to verify. Apparently they haven't migrated yet either ^_^Neutralize
I'm still waiting for 5.4 when you can also write $$class::$$attribute.Wilen
I think that property_exists($class, $attribute) is clearer, though it won't distinguish between static and non-static members, and it only works on non-public members as of 5.3.Catricecatrina
@mario: Just checked trunk and the part before T_PAAMAYIM_NEKUDOTAYIM is still only class_name or reference_variable. $$class would need at least a variable_without_objects ;)Dnieper
get_class_vars might be useful.Catricecatrina
@levu: I added a possibility using Reflection ;)Dnieper
M
1

In 5.3, you can simply do

var_dump(property_exists($class, $attribute));
Muniments answered 25/4, 2011 at 14:28 Comment(1)
property_exists('class','attribute') to clarify this answerMomentary

© 2022 - 2024 — McMap. All rights reserved.