Skip to main content

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:

index.php
<?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:

Prompt
Create a PHP class called pi with a public static property $value set to 3.14159. Echo the static property directly using the class name.
Output: PHP script

Static property access syntax

The general form for reaching a static property:

index.php
<?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:

Prompt
Create a PHP class called pi with a public static property $value set to 3.14159 and a method staticValue() that returns the static property using the self keyword. Create an instance and echo the result.
Output: PHP script

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:

Prompt
Create a PHP class pi with a public static property $value set to 3.14159. Create a child class x that has a method xStatic() returning the parent static property. Echo the value both directly and via the method.
Output: PHP script