What are PHP static properties?

Overview

Properties are just another name for variables, but they reside inside a class. To access the property of a class, we have to create a new instance of the class using the new keyword. We can access static properties directly without instantiating the class.

Let's see an example.

Example

Let's see an example:

<?php
class Bio {
public static $name = "John Doe";
}
// Accessing property value
echo Bio::$name;
?>

Code explanation

From the above code:

  • Line 2: We create a class Bio.
  • Line 3: We create a property name. Notice the syntax of how we created the property.
    • First, we use the public keyword so that other classes can access it.
    • Then, we use the static keyword so it can be a static property.
  • Line 6: We echo or print the $name value by accessing the static property.

We use the :: after the Bio class in echo Bio::$name, and we do not need to create a new instance of the Bio class.

Free Resources