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 w ww  . j  a  v a  2s . 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);/*w  ww.  ja v a 2  s  .com*/
          }

          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