Range resolution operator (::)

WBOY
Release: 2016-07-29 08:57:07
Original
1560 people have browsed it

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

When referencing these items outside of the class definition, use the class name.

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

The choice of Paamayim Nekudotayim as the name of the double colon operator seems a bit strange. However, this was a decision the Zend development team made when writing Zend Engine 0.5 (used in PHP 3). In fact, this word in Hebrew means double colon.

Example #1 Using :: operator

<?php
class MyClass {
    const CONST_VALUE = &#39;A constant value&#39;;
}

$classname = &#39;MyClass&#39;;
echo $classname::CONST_VALUE; // 自 PHP 5.3.0 起

echo MyClass::CONST_VALUE;
?>
Copy after login
self, parent and static These three special keywords are Used to access properties or methods within a class definition.
Example #2 Use inside the class definition ::

<?php
class OtherClass extends MyClass
{
    public static $my_static = &#39;static var&#39;;

    public static function doubleColon() {
        echo parent::CONST_VALUE . "\n";
        echo self::$my_static . "\n";
    }
}

$classname = &#39;OtherClass&#39;;
echo $classname::doubleColon(); // 自 PHP 5.3.0 起

OtherClass::doubleColon();
?>
Copy after login

Example #3 Call the method of the parent class

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

class OtherClass extends MyClass
{
    // 覆盖了父类的定义
    public function myFunc()
    {
        // 但还是可以调用父类中被覆盖的方法
        parent::myFunc();
        echo "OtherClass::myFunc()\n";
    }
}

$class = new OtherClass();
$class->myFunc();
?>
Copy after login

The above introduces the range parsing operator (::), including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template