PHP - Static Properties
The static keyword also creates static properties.
You can read a static property directly, without ever making an object from its class.
Declare a Static Property
Declaring a static property works by adding the static keyword to it:
Static property declaration syntax
static goes ahead of the property name:
<?php
class ClassName {
public static $statProp = "PromptCookbook";
}
?>
Access a Static Property
Reading a static property takes three parts: the class name, a double colon (::), and the property name.
The next example declares a static property called $value and echoes it directly in that form. No object is needed:
Example
Read a static property through its class name:
Output: PHP script
<?php
class pi {
// static property
public static $value = 3.14159;
}
// Get static property directly
echo pi::$value;
?>
Static property access syntax
The general form for reaching a static property:
<?php
ClassName::$statProp;
?>
PHP - More on Static Properties
Static and non-static properties can exist in the same class. A method of that class reaches a static property by writing self and a double colon (::) before the property name:
Example
A method reads a static property of its own class through self:
Output: PHP script
<?php
class pi {
public static $value=3.14159;
public function staticValue() {
return self::$value;
}
}
$pi = new pi();
echo $pi->staticValue();
?>
Example
Inside a child class, reach the parent's static property with the parent keyword. The example also reads it directly through the child class name:
Output: PHP script
<?php
class pi {
public static $value=3.14159;
}
class x extends pi {
public function xStatic() {
return parent::$value;
}
}
// Get value of static property directly via child class
echo x::$value;
// or get value of static property via xStatic() method
$x = new x();
echo $x->xStatic();
?>