Usage analysis of PHP range resolution operator (::) [access static members and class constants]

Time:2021-1-11

This article illustrates the usage of the PHP range resolution operator (::). The details are as follows:

Range resolution operator (:)

The range resolution operator (also known as paamayim nekudotayim), or more simply a pair of colons, can be used to access static members, class constants, and to override properties and methods in a class.

When referring to these projects outside of the class definition, use the class name.

Since PHP 5.3.0, classes can be referenced by variables whose values cannot be keywords (such as self, parent and static).

It seems strange to choose paamayim nekudotayim as the name of the double colon operator. However, this was a decision made by the Zend development team when they wrote Zend engine 0.5 (used in PHP 3). In fact, the word means double colon in Hebrew.

Use outside of class::

Self, parent and static are three special keywords used to access the properties or methods of a class within its definition.

<?php
class MyClass {
  const CONST_VALUE = 'A constant value';
}

$classname = 'MyClass';
echo $classname::CONST_ Value; // from PHP 5.3.0

echo MyClass::CONST_VALUE;

Use inside the class definition::

When a subclass covers a method in its parent class, PHP does not call the method that has been covered in the parent class. Whether to call the method of the parent class depends on the subclass. This mechanism also works on constructors and destructors, overloads, and magic methods.

<?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';
Echo $classname:: doublecolon(); // since PHP 5.3.0

OtherClass::doubleColon();

Call the method of the parent class

<?php
class MyClass
{
  protected function myFunc() {
    echo "MyClass::myFunc()\n";
  }
}

class OtherClass extends MyClass
{
  //The definition of the parent class is overridden
  public function myFunc()
  {
    //But you can still call the overridden method in the parent class
    parent::myFunc();
    echo "OtherClass::myFunc()\n";
  }
}

$class = new OtherClass();
$class->myFunc();

Results of operation:

MyClass::myFunc()
OtherClass::myFunc()

More about PHP related content, interested readers can see the special topics of this website: “PHP object-oriented programming introductory tutorial”, “PHP array operation skills encyclopedia”, “PHP basic grammar introductory tutorial”, “PHP operation and operator Usage Summary”, “PHP string Usage Summary”, “PHP + MySQL database operation introductory tutorial” and “PHP common database operation” Summary of writing skills

I hope this article is helpful for PHP programming.