PHP Static Properties and Methods


Introduction

In a PHP class, properties and methods declared with static keyword cannot be accessed by its object with the help of -> operator. In fact, object is not required to access any instance of class. Default visibility of static items in a class is public

static properties

To access a static property from outside class, we need to use scope resolution operator (::) along with name of class. A string variable evaluating to name of class can also provide to static property

<?php
class testclass{
   static $name="test";
}
echo testclass::$name;
$var="testclass";
echo $var::$name;
?>

to use static propery inside any method of the same class, use self keyword instead of -> operator that is used for accessing instance properties.

<?php
class testclass{
   static $name="test";
   public function test(){
      echo self::$name;
   }
}
$obj=new testclass();
$obj->test();
?>

Any static property declared in parent class can be referred to inside a child class method, by using parent keyword along with scope resolution operator

<?php
class testclass{
   static $name="test";
   public function test(){
      echo self::$name;
   }
}
class myclass extends testclass{
   public function mytest(){
      echo parent::$name;
   }
}
$obj=new myclass();
$obj->mytest();
?>

static methods

When a method is declared as static, the pseudo-variable $this is not available to it. Hence, instance attributes of a class cannot be accessed in it. The static method is called by name of class along with scope resolution operator

In following example, the class has a static property $count that increnments every time constructor is executed (i.e. for each object). Inside the class, there is a static function that retrieves value of static property

Example

 Live Demo

<?php
class testclass{
   static $count=0;
   function __construct(){
      self::$count++;
   }
   static function showcount(){
      echo "count = " . self::$count;
   }
}
$a=new testclass();
$b=new testclass();
$c=new testclass();
testclass::showcount();
?>

Output

This will produce following output −

count = 3

Updated on: 18-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements