Static Properties in PHP OOP

Static methods in PHP OOP
Namespaces in PHP
Static keyword in PHP

What are static properties in PHP?

Just like we studied static methods in the previous tutorial, static properties in PHP are accessible within and outside the class directly.

  • The static keyword is used to define the static properties of a class.
  • To access the static properties of a class, we use the scope resolution operator ::
<?php
class Example {
  public static $static_var = "php.org";
}
?>

Example of static properties

<?php
class pi {
  public static $value = 3.14159;
}

// Get static property
echo pi::$value;
?>
  • In the above example, we create a class having static property.
  • Access the value of the static property without creating the object of the class.

A class can contain both static and non-static properties. As we know from the previous section that static properties are accessible outside the class using the scope resolution operator. To access the static property inside the class, we use the self keyword. For instance.

<?php
class pi {
  public static $value=3.14159;
  public function staticValue() {
    return self::$value;
  }
}

$pi = new pi();
echo $pi->staticValue();
?>

How to access the static property in the child class?

  • Consider a scenario in which we have a child class that extends the parent class having some static value.
  • Access the value of static property on the child class using parent keyword. Parent keyword assist the child class to grab the value from the parent class. Look at the following example.
<?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();
?>

Reference to the official PHP documentation for static keyword.

Static methods in PHP OOP
Namespaces in PHP

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top