Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do public static final class variables exist

Tags:

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

like image 707
David Avatar asked Aug 16 '13 12:08

David


People also ask

Should static final variables be public?

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.

Can final variables be public?

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.

Can static variables be public?

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.

Can a static class have variables?

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.


1 Answers

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 =).

like image 133
brianmearns Avatar answered Nov 22 '22 05:11

brianmearns