Is it possible to check if a variable is static in PHP?

Is it possible to check if a variable is static in PHP? I am trying to create a magic __get method that also considers static variables. I found that property_exists() returns true when the variable is also static. But I will need to use :: instead of -> , would I expect?

+6
source share
2 answers

You can check if the variable is static through Reflection:

 class Foo { static $bar; } $prop = new ReflectionProperty('Foo', 'bar'); var_dump($prop->isStatic()); // TRUE 

However, this still will not allow you to use them with the magic methods __get or __set , because they work only in the context of the object. From the PHP manual on magic methods:

Property overloading only works in the context of an object. These magic methods will not be triggered in a static context. Therefore, these methods should not be declared static. Starting with PHP 5.3.0, a warning is issued if one of the overload magic methods is declared static.

Also check out this discussion on the PHP Internals mailing list about introducing __getStatic :

+6
source

I don't think you can access an undeclared static property using the __get () magic method. This will throw a PHP Fatal error. At least since PHP version 5.3.

This is the result if you try to access the property as a static ClassName::$propertyName , of course.

0
source

Source: https://habr.com/ru/post/891939/


All Articles