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. |
Related Links
Syntax :- The static
keyword is used to declare static methods and properties..
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.
";
// Call static method
MyClass::sayHello();
?>
Output :-
ABC
Hello
Hello
Example 2 :- The following example display difference between static members and instance members.
y . "
";
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 "
The total is : " . $total;
?>
Output :-
X = 10 , Y = 10
X = 11 , Y = 10
X = 12 , Y = 10
The total is : 46
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.
Related Links
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.