·  PHP – Syntax – Keywords – static

 

- Info:

  - Declaring class properties or methods as static makes them accessible without needing an instantiation of the class.

  - Static properties cannot be accessed through the object using the arrow operator -> but static functions can.

  - Both static properties and methods can be accessed through both class and object using the '::' operator.

  - Pseudo-variable $this is not available inside static methods.

  - Like other PHP static variables, static properties may only be initialized using literal or constant like: integer, array, ...

    You may not initialize it to expression like another variable, function return value, or an object.

    Later, during code execution, you can put whatever you want in static property.

  - Calling non-static methods statically generates an E_STRICT level warning.

  - Use self to access static members from within static function.

 

- Example:

  - Create PHP Console Application Test.php.

 

    Test.php

    <?php

   

      class MyClass {

        public static $prop = "Property";

        public static function myfunc() {

          print("Function - ".self::$prop);

          //print($this->prop);       //Using $this when not in object context.

        }

      }

   

      //REFERENCE THROUGH CLASS.

      print(MyClass::$prop   ."\n");

      print(MyClass::myfunc()."\n");

   

      //REFERENCE THROUGH CLASS NAME FROM STRING.

      $classname = 'MyClass';

      print($classname::$prop   ."\n");

      print($classname::myfunc()."\n");

   

      //REFERENCE THROUGH OBJECT.

      $obj = new MyClass();

      print($obj::$prop   ."\n");

      print($obj::myfunc()."\n");

      print($obj->prop    ."\n");     //Undefined property: MyClass::$prop

      print($obj->myfunc()."\n");

   

    ?>