PHP Reference ยท Operators
The PHP scope resolution operator (::)
Reference for the PHP :: operator: access class constants, static properties and methods, parent::, self::, static::, ::class and enum cases.
The scope resolution operator :: (often called "double colon") reaches members that belong to a class instead of an object: constants, static properties, static methods and enum cases. It is also how you call an overridden parent method with parent::.
On the left you can write a class name, one of the keywords self, parent and static, a string variable that holds a class name, or an object. The special form ClassName::class gives the fully qualified class name as a string at compile time.
echo Circle::PI; // class constant echo Counter::$total; // static property echo Math::square(4); // static method
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
ClassName::CONSTANT ClassName::$staticProperty ClassName::staticMethod() ClassName::class self::member parent::member static::member $object::member $classString::member
| Left side | Refers to |
|---|---|
ClassName |
That exact class (or the one it inherits the member from) |
self |
The class where the code is written |
parent |
The direct parent of the class where the code is written |
static |
The class that was called at run time (late static binding) |
$object, $string |
The object's class, or the class named by the string |
Usage notes
selfversusstatic.self::is fixed when you write the code;static::follows the actual class, which is what factories and fluent static APIs need. See late static binding.::classdoes not load the class.Foo::classis resolved by the compiler using namespaces anduse, even ifFoodoes not exist.$object::class(PHP 8.0) works likeget_class($object).- Non-static methods via
::are only allowed when you call a parent or ancestor method from inside an instance (parent::describe()). Calling a non-static method statically from outside throwsError. - Dynamic names.
$class::CONSTANT,$class::$propand$class::method()work; for a dynamic constant name useconstant("Counter::START"). - Dynamic class constant fetch (PHP 8.3).
Suit::{$name}reads a constant or enum case whose name is in a variable. - Visibility still applies. Private and protected members are reachable only from permitted scopes.
- Enum cases are accessed with
::too, and enums have static methods likefrom(),tryFrom()andcases(). - Don't confuse
::with->.->needs an object instance;::works on classes (and on objects for static members).