Static methods and properties

I assume you know the difference between class and an object. If not, read this!

A static method is basically the same as a non-static, but there is one difference: a static method is accessible without needing an instantiation of the class. Because you access a static element via a class and not an instance, you do not need variable that references an object. Instead you use the class name following ::

To access a static method or property from within the same class you should use self keyword instead of pseudo variable $this.

Benefits of using static elements

Static elements are available from anywhere in the script

This is true as long as you have access to the class. This means you don’t have to pass an object around as parameter (you could avoid this by using global variables but don’t do this!!!).

Static property is available to every object

It doesn’t matter how many instances of a class you have. To each one the same value will be available.

No need to create object to access property

If you need to call a simple function you don’t need to instantiate an object and make a call separately.




Leave a Reply

Your email address will not be published. Required fields are marked *

Please prove me that you are not spamer :) * Time limit is exhausted. Please reload CAPTCHA.