PHP Static Methods and Properties


There are two types of class members in PHP.

  • Static Members
  • Instance Members

The main differences are :

Static Member Instance Member
It accessed by class name It accessed by object name
It shares a common memory for all objects. It creates new memory for every objects.
It is not depends to object. It is depends to object.
It create memory only once in their life. It create memory whenever a new object is created.
Instances of a class do not need to be created in order to call static methods and properties directly. We must create a object of a class in order to call instance members.

Syntax :- The static keyword is used to declare static methods and properties..

<?php
class MyClass {

  public static $staticVariable;

  public static function staticMethod() {
    echo "Hello World!";
  }
}
?>

Syntax :- Accessing a static methods and properties:

//  For Static Property

ClassName::staticPropertyName;

//  For Static Method

ClassName::staticMethodName();

Example 1 :- The following example contains a static property and method.

<?php
class MyClass {

  //    A static property

  public static $name = "ABC";

  //    A static method

  public static function sayHello() {
    echo "Hello";
  }
}

//  Call static property

echo MyClass::$name;

echo "<br />";

//  Call static method

MyClass::sayHello();
?>

Output :-

ABC
Hello

Example 2 :- The following example display difference between static members and instance members.

<?php
class MyClass {
  //    A static property

  public static $x = 10;

  //    A instance property

  public $y = 10;

  function showXY()
  {
	echo "X = " . MyClass::$x . " , Y = " . $this->y . "<br />";
	MyClass::$x += 1;
	$this->y += 1;
  }
}

$obj1 = new MyClass();
$obj2 = new MyClass();
$obj3 = new MyClass();

$obj1->showXY();
$obj2->showXY();
$obj3->showXY();

$total = MyClass::$x + $obj1->y + $obj2->y + $obj3->y;
echo "<br /><br />The total is : " . $total;
?>

Output :-

X = 10 , Y = 10
X = 11 , Y = 10
X = 12 , Y = 10

The total is : 46

Note:- Static and non-static methods are both possible in a same class.

Use the self keyword followed by a double colon (::) to access a static method from a method in the same class.

You can also search for these topics, variables in php static, methods in php static, php static array, class static method in php, access property in php static method, php constructor static methods, working of static property variables in php, php static property default value, check the existing and instance of php static method, syntax for php static method, Example for static method in php, keywords used static method in php, how to return the php static method.