Understanding static variables with PHP

As you already know, in the classes in PHP as well as in other object-oriented programming lenguages there are a special kind of variables which have the key word static before the variable itself. Well, today I will try to explain you how these special variable actually work.

The first thing we need to keep in mind is that a static variable only belongs to the class where it was declared and this variable is a non-inheritance one. After to know this, there is other important thing to keep in mind and it is that in order to get that variable, we need to type the name of the class where the variable belongs to and after two colons the name of the variable. You can watch this in the following code lines:

        class Unicorn{
                static $minimumNetWorth = "+1B$";

        echo "Minimum Net worth of a unicorn = ".Unicorn::$minimumNetWorth."\n";

As you can see, the first thing that we do is to declarate a class with only one variable; the static variable. At the moment to use this variable it is not as traditionally as with the normal variables, but with this we need to use a different sintaxis.

I hope this have been pretty useful for you and with this you can understand the weird sintaxis used sometimes in php code lines.

Escribe tu comentario
+ 2