📜 ⬆️ ⬇️

Access to static data

Starting with version 5.3, it became possible to access the static data of classes using a variable. Thanks to this, we almost forgot about the error "syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM", which occurred while trying to use the "::" operator as something "wrong."

But, it seems to me, not everyone knows about the opportunities that have opened up.

Create an interface, class and object for experiments.

interface bar{ const SOME_CONST = 'SOME_CONST'; static public function static_public_function(); } class foo implements bar{ static public $static_public_property = 'static_public_propery'; static public function static_public_function(){ return 'static_public_function'; } } $object = new foo(); 

')
A code that works both in 5.3 and earlier. Having an object, it was necessary to find out its class.

 echo foo::SOME_CONST . PHP_EOL; // SOME_CONST echo foo::$static_public_property . PHP_EOL; // static_public_property echo foo::static_public_function() . PHP_EOL; // static_public_function echo bar::SOME_CONST . PHP_EOL; // SOME_CONST 


Code that works since PHP 5.3. Now there is no need to specify the class.

 echo $object::$static_public_property . PHP_EOL; // static_public_property echo $object::SOME_CONST . PHP_EOL; // SOME_CONST echo $object::static_public_function() . PHP_EOL; // static_public_function 


Constants and static methods could be declared in interfaces from the very beginning of the appearance of interfaces in PHP. But in order to work with them you had to specify the name of the interface or class. Now you can use the object to access this data. We can say that since version 5.3 constants and static methods have become a full-fledged part of the interface.

This allows you to reduce the number of uses of class names and interfaces. And also use IDE autocompletion having an object “on hand”.

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


All Articles