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.
Example
class Foo { // ... } public function aNormalMethod() { // ... } } $something = Foo::aStaticMethod(); //normally we have to create an object $fooObj = new Foo(); $someOtherThing = $fooObj->aNormalMethod();
| < Prev | Next > |
|---|