Advertisement
Google Ad Slot: content-top
PHP OOP - Static Properties
PHP - Static Properties
A static property:
- Belongs to the class itself, not any object instance.
- Is shared across all instances of the class.
- Static properties are declared with the
statickeyword: - Can be accessed using the
ClassName::$propertyNameorself::$propertyNamefrom within the class.
Syntax
<?php
class ClassName {
public static $staticProp = "W3Schools";
}
?>
To access a static property use the class name, double colon (::), and the property name:
Syntax
ClassName::$staticProp;
Let's look at an example:
Explanation:
public static $name = "PHP";
Declares a static property called $name that belongs to the class MyClass.
MyClass::$name
Outside the class, you use the class name with :: to access static properties or methods.
- You don’t need to create an object to access static members. That’s the beauty of
static.
PHP - More on Static Properties
A static property can be accessed from a method in the same class using the self keyword and double colon (::):
Explanation:
public static $name = "PHP";
Declares a static property called $name that belongs to the class MyClass.
self::$name
Inside the class, you use self:: to refer to static members.
MyClass::$name
Outside the class, you use the class name with :: to access static properties or methods.
To call a static property from a parent class using the parent keyword inside the child class.