PHP Class Attribute and class static variable access method example, php example
This article describes how to access class attributes and class static variables in PHP. We will share this with you for your reference. The details are as follows:
<? Php/* PHP class Attribute and class static variable access * Created on 2016-7-13 */class test {const constvar = 'Hello world'; static $ staticvar = 'Hello world '; function getStaticvar () {return self: $ staticvar ;}}$ obj = new test (); echo test: constvar; // output 'Hello world' echo @ test :: staticvar; // error. Before staticvar, you must add $ to access it. This is one of the areas that are easy to confuse with class constants (per-class constants). echo test: $ staticvar; // output 'Hello world' $ str = 'test'; // echo $ str: $ staticvar; // error. The class name cannot be dynamic here/ /Echo $ str: constvar; // the cause of the error is the same as above. // when a variable in the class name is in an uncertain (dynamic) state, the response class variable $ obj2 = new $ str (); echo $ obj2-> getStaticvar ();?>
Running result: hello world