Home >Backend Development >PHP Tutorial >PHP sample code sharing using range resolution operator
Object-orientedProgramming will use some of its own operators, such as ->, this symbol is used Access its own members within an object. The other one is the range resolution operator: two colons connected together (::). This notation is used to access members within a class (not within an object). The usage is as follows: ClassName::methodName();
ClassName::propertyName;
This structure may be used in two places:
1. When using a class, the parent class and the subclass have the same
attributes and Use this to avoid confusion when using method. 2. When outside the class, use this operator to access the members of the class without
creating an object. Just as we can use $this in a class to
referencethe instance of the current object, the keyword self is used as a reference to the current class. class SomeClass {
function construct() {
self::do();
}
protected function do(){
echo "done!";
}
}
In this code, self::do() will trigger the do() method of the current class.
To reference a member of the parent class, you can use the keyword parent and the range resolution operator to reference:
class SomeOtherClass extends SomeClass { function construct() { parent::do(); } }
In most cases, we use the range resolution operator to access the repeated method of writing. We can also use it to access
staticand constant members. Note: Like static properties, class constants can be accessed by all instances of the class (or its subclasses). But its value cannot be changed. Class constants are created using the
const keyword, followed by the constant name (without the dollar sign). Constants cannot be accessed through objects, such as $obj->PI or $obj::PI, but we can use ClassName::CONSTANT_NAME anywhere. You can also use self::CONSTANT_NAME in methods within a class. Sample program:
<?php class Rectangle { protected static $_count = 0; protected $width; protected $height; function construct($width, $height) { $this->width = $width; $this->height = $height; self::$_count++; echo "已成功创建".self::$_count."个Rectangle对象<br>"; } function destruct() { echo "销毁一个Rectangle对象<br>"; } function getArea() { echo "Rectangle面积是:".($this->width * $this->height."<br>"); } function getConunt() { return self::$_count; } } class Square extends Rectangle { function construct($side) { $this->width = $side; $this->height = $side; parent::$_count++; echo "已成功创建".parent::$_count."个Rectangle(Square)对象<br>"; } } $rec = new Rectangle(10, 5); $rec->getArea(); $square = new Square(10); $square->getArea(); ?>
Running results:
The above is the detailed content of PHP sample code sharing using range resolution operator. For more information, please follow other related articles on the PHP Chinese website!