In Jave you can define a public static final
variable in a class. Is there an equivalent to this in PHP?
I'd like to do the following:
<?php class MyClass{ public final static $finalVariable = "something"; } MyClass::$finalVariable
and not ever have to worry about $finalVariable
changing and not having a new instance for every instantiation of MyClass
Static variables are created when the program starts and destroyed when the program stops. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
A public static final variable is a compile-time constant, but a public final is just a final variable, i.e. you cannot reassign value to it but it's not a compile-time constant. This may look puzzling, but the actual difference allows how the compiler treats those two variables.
The non-static class variables belong to instances and the static variable belongs to class. Just like an instance variables can be private or public, static variables can also be private or public.
Class variables are also known as static variables, and they are declared outside a method, with the help of the keyword 'static'. Static variable is the one that is common to all the instances of the class. A single copy of the variable is shared among all objects.
From this page in the PHP manual:
Note: Properties cannot be declared final, only classes and methods may be declared as final.
However, you can use class constants as described here.
Your example would look something like this:
<?php class MyClass{ const finalVariable = "something"; } MyClass::finalVariable; ?>
Except of course that finalVariable
isn't really an appropriate name because it's not variable =).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With