In this tutorial, we will learn about Static Properties in PHP. Same as static methods we can declare static properties in PHP. We can access these static variables without creating an object of the class. Static properties can be declared using the static keyword. Please check out the following example program to know how to declare static properties.
Page Contents
Declaring Static Properties Example Program:
<?php
class Example{
//This is static property
public static $name = "Owlbuddy";
}
?>
After declaring any static property you can access it very easily using the double colon(::) operator. Just write the class name that contains that particular property then a double colon(::) followed by property name. Please check out the following example program.
Accessing Static Property Example Program:
<?php
class Example{
//This is static property
public static $name = "Owlbuddy";
}
echo Example::$name;
?>
As you can see in the above example how easy it is to fetch static properties in PHP. Furthermore, there are many situations when you need to access any static property in the same class any method or constructor. In this kind of scenario, you can use the self keyword.
Fetching Static Property in Same class:
<?php
class Example{
//This is static property
public static $name = "Owlbuddy";
public function show(){
echo "Welcome to ".self::$name;
}
}
$obj = new Example;
$obj->show();
?>
In the above example, we learned how we can access static properties in methods of the same class. But in case you want to access static properties from the parent class you have to use the parent keyword in the child class.
Fetching Static Property from Parent class:
<?php
class Example{
//This is static property
public static $name = "Owlbuddy";
}
class Child extends Example{
public function show(){
echo "Welcome to ".parent::$name;
}
}
$obj = new Child;
$obj->show();
?>