Giới thiệu
Trong PHP, dấu hai chấm kép :: được định nghĩa là Scope Resolution Operator. Dùng khi muốn truy cập constants, properties và methods định nghĩa ở cấp độ class (static). Khi tham chiếu các item này bên ngoài class definition, dùng tên class cùng scope resolution operator. Toán tử này còn gọi là Paamayim Nekudotayim (tiếng Hebrew nghĩa là double colon).
Cú pháp
<?php
class A {
const PI = 3.142;
static $x = 10;
}
echo A::PI;
echo A::$x;
$var = 'A';
echo $var::PI;
echo $var::$x;
?>
Bên trong class
Để truy cập class-level item bên trong method, dùng từ khóa self:
<?php
class A {
const PI = 3.142;
static $x = 10;
static function show() {
echo self::PI . self::$x;
}
}
A::show();
?>
Trong child class
Nếu parent class method bị override bởi child class và cần gọi parent method tương ứng, phải tiền tố bằng từ khóa parent và scope resolution operator.
Ví dụ
<?php
class TestClass {
public function sayhello() {
echo "Hello World\n";
}
}
class MyClass extends TestClass {
public function sayhello() {
parent::sayhello();
echo "Hello PHP";
}
}
$obj = new MyClass();
$obj->sayhello();
?>
Kết quả
Hello World Hello PHP