Home >Backend Development >PHP Tutorial >Basic knowledge of PHP: classes and objects (4) range resolution operator (::)_PHP tutorial
The scope resolution operator (also known as Paamayim Nekudotayim) or more simply a pair of colons can be used to access static members, methods and constants, and can also be used to access members and methods in overridden classes.
When accessing these static members, methods and constants outside the class, the class name must be used.
Paamayim Nekudotayim means double colon in Hebrew.
Use :: operator outside the class
class MyClass {
const CONST_VALUE = 'A constant value';
}
echo MyClass::CONST_VALUE;
The two special keywords self and parent are used to access members or methods inside the class.
Example:
class OtherClass extends MyClass
{
public static $my_static = 'static var';
public static function doubleColon() {
echo parent ::CONST_VALUE . " n";
echo self::$my_static . " n";
}
}
OtherClass::doubleColon();
When a subclass When overriding a method in its parent class, PHP will no longer execute the overridden methods in the parent class until these methods are called in the child class. (Is it nonsense? No, this is a little difference between PHP and other mainstream languages). This mechanism also works for constructors and destructors, overloads, and magic functions.
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc() n";
}
}
class OtherClass extends MyClass
{
// Override the method in the parent class
public function myFunc()
{
// But you can still call the overridden method
parent:: myFunc();
echo "OtherClass::myFunc() n";
}
}
$class = new OtherClass();
$class->myFunc( );
--------------------------------- -----------------------------------------------
??Important??When accessing static methods or members, you must use the class name:: method.
Another note: PHP will not actively call the methods of the parent class, including constructors and destructors.
See this text: http://163xiaofan.blog.163.com/blog/static/1713578020061027101820973