Static Keyword
- A static keyword is very important concept in OOP.
- Static method and properties play important role in Development.
- You know that to access any method or attribute in a class you must create an instance (using new keyword,otherwise you can't access them).
- By using static methods and properties,you can access a static method or property directly without creating any instance of that class.
- A
static memberis same as global member for that class and all instances of that class. - A
static propertiesmaintain the last state of what it was assigned.
<?php
class Static_Demo
{
private static $count = 0;
function __construct()
{
self::$count+=1;
}
public static function checkCount()
{
echo "Current Count From Static Method is ".self::$count."</br>";
}
public function checkCountNonStatic()
{
echo "Current Count From Non Static Method is ".self::$count."</br>";
}
}
$st1 = new Static_Demo();
Static_Demo::checkCount();
$st2 = new Static_Demo();
$st1->checkCountNonStatic();//returns the val of $count as 2
$st1->checkCount();
$st2->checkCountNonStatic();
$st3 = new Static_Demo();
Static_Demo::checkCount();
?>
Output :
Current Count From Static Method is 1 Current Count From Non Static Method is 2 Current Count From Static Method is 2 Current Count From Non Static Method is 2 Current Count From Static Method is 3
Note :
$this
pseudo object does not use inside a static method.So class does not
instantiated You should
self keyword
rather than $this.


