Paamayim Nekudotayim In PHP

30th January 2009 - 2 minutes read time

What? Don't worry, I can't say it either. It is officially called the Scope Resolution Operator (but also just a double colon) and is used to reference static properties and functions of a class. It is also used to reference overridden functions of classes.

To reference a constant of a class you do something similar to the following.

  1. class MyClass {
  2. const CONST_VALUE = 'A constant value';
  3. }
  4.  
  5. echo MyClass::CONST_VALUE;

To call a static function or a parameter you need to include the word static in the function or parameter definition. You can then reference this function through the scope resolution operator.

  1. class MyClass {
  2. public static $my_static = 'static var';
  3.  
  4. public static function thisIsFunction() {
  5.  
  6. }
  7. }
  8.  
  9. echo MyClass::$my_static; // prints 'static var'
  10. MyClass::thisIsFunction(); // calls thisIsFunction() in MyClass

You can also use the scope resolution operator to reference functions and parameters in parent classes. This is accomplished by using the parent operator. The following code has two class definitions, one of which basically exists to call the function from the parent.

  1. class MyClass {
  2. public static $my_static = 'static var';
  3.  
  4. public static function thisIsFunction() {
  5.  
  6. }
  7. }
  8.  
  9. class ChildClass extends MyClass{
  10.  
  11. public static function childFunction() {
  12. parent::thisIsFunction();
  13. }
  14. }
  15.  
  16. OtherClass::childFunction(); // calls childFunction() in MyClass

The call to the childFunction() function basically calls the function thisIsFunction() in the parent class. This is useful if you want to override the parent function, but still use most of the basic functionality. For example, the child class could take in a parameter, which it then formats or alters and passes this to the parent class.

Add new comment

The content of this field is kept private and will not be shown publicly.