Parent and self in PHP


Parent and self


The Scope Resolution Operator in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.


Example #1 :: from outside the class definition

<?php

class MyClass {

   const CONST_VALUE = 'A constant value';

}

$classname = 'MyClass';

echo $classname::CONST_VALUE; // As of PHP 5.3.0

echo MyClass::CONST_VALUE;

?>

Three special keywords self, parent and static are used to access properties or methods from inside the class definition.


Example #2 :: from inside the class definition

<?php

class OtherClass extends MyClass

{

   public static $my_static = 'static var';

   public static function doubleColon() {

       echo parent::CONST_VALUE . "\n";

       echo self::$my_static . "\n";

   }

}

$classname = 'OtherClass';

$classname::doubleColon(); // As of PHP 5.3.0

OtherClass::doubleColon();

?>


Example #3 Calling a parent's method

<?php

class MyClass

{

   protected function myFunc() {

       echo "MyClass::myFunc()\n";

   }

}

class OtherClass extends MyClass

{

   // Override parent's definition

   public function myFunc()

   {

       // But still call the parent function

       parent::myFunc();

       echo "OtherClass::myFunc()\n";

   }

}

$class = new OtherClass();

$class->myFunc();

?>

Custom Search

%d bloggers like this: