PHP - Accessing static method or property, or a class constant

Introduction

To access a static method or property, or a class constant, from within a method of the same class, use the same syntax as you would outside the class:

Demo

<?php
        class MyClass {

          const MYCONST = 123;
          public static $staticVar = 456;

          public function myMethod() {
            echo"MYCONST =". MyClass::MYCONST.",";
            echo"\$staticVar =". MyClass::$staticVar."\n";
          }/*from   ww  w .j  a v a  2 s.  c o m*/
        }

        $obj = new MyClass;
        $obj->myMethod();  // Displays"MYCONST = 123, $staticVar = 456"
?>

Result

You can also use the self keyword:

Demo

<?php
        class Truck {

          public static function calcMpg($miles, $gallons) {
            return ($miles / $gallons);/*from  w  ww .j a  v a 2s  .c  o m*/
          }

          public static function displayMpg($miles, $gallons) {
            echo"This Truck's MPG is:". self::calcMpg($miles, $gallons);
          }
        }

        echo Truck::displayMpg(168, 6); // Displays"This Truck's MPG is: 28"
?>

Result

Related Topic