PHP range resolution operator (::)

伊谢尔伦
Release: 2016-11-23 14:13:35
Original
1052 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, and the value of the variable 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 Use the :: operator outside the class

class MyClass
{
    const CONST_VALUE = 1;
}
$classname = 'MyClass';
echo $classname::CONST_VALUE; //自PHP5.3.0起
echo MyClass::CONST_VALUE;
Copy after login

The three special keywords self, parent and static are used to access its properties or methods inside the class definition.

Example #2 Used inside a class definition::

function __autoload($classname){
    require_once($classname.".php");
}
class OtherClass extends MyClass
{
    public static $my_static = 1;
    public static function doubleColon(){
        echo parent::CONST_VALUE.'
'; echo self::$my_static,'
'; } } $classname = 'OtherClass'; echo $classname::doubleColon(); OtherClass::doubleColon();
Copy after login

When a subclass overrides a method in its parent class, PHP will not call the overridden method in the parent class. Whether the method of the parent class is called depends on the child class. This mechanism also works with constructors and destructors, overloading, and magic methods.

Example #3 Call the method of the parent class

class MyClass
{
    protected function myFunc()
    {
        echo 'MyClass::myFunc()
'; } } class OtherClass extends MyClass { //覆盖了父类的定义 public function myFunc() { //但还是可以调用父类中被覆盖的方法 parent::myFunc(); echo 'OtherClass::myFunc()
'; } } $class = new OtherClass(); $class -> myFunc();
Copy after login

Output result:

MyClass::myFunc()

OtherClass::myFunc()


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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!