I realize that this question has already been asked elsewhere for different programming languages... But this is not a 100% indicator for the same answer in the PHP domain, so I am asking this question.
Could someone please tell me what, specifically in PHP, is the difference between "final static" and "const" ?
The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object's entire deep state strictly fixed at compile-time and that the object with this state will be considered frozen and completely immutable.
Constants are set at compile time itself and assigned for value types only. e.g. Static variable is a property of a Class rather than the instance of class. It is stored on the data segment area of memory and the same value is get shared to all instances of that class.
The const variable is basically used for declaring a constant value that cannot be modified. A static keyword is been used to declare a variable or a method as static. A const keyword is been used to assign a constant or a fixed value to a variable.
The static keyword means the value is the same for every instance of the class. The final keyword means once the variable is assigned a value it can never be changed. The combination of static final in Java is how to create a constant value.
final
The methods or classes can not be modified by a child class. This prevents class inheritance, method-overriding and/or redefinition of methods.
Only class definitions and/or methods inside a class can be defined as
final
.
static
Declares class methods or properties as a static value so that you have access to them without instantiating an object. These are shared between parent and child-classes.
A class definition can not be
static
unlikefinal
.
const
These create a constant value for a class. The constant values will get changed and can NOT be changed by a method in either parent or child-class.
Class constants are allocated per instance of the class.
const
is a type specifier in itself. It can not be put along with public
/private
/static
etc. final
, as mentioned before can be used along with any method or class definitions and hence; applicable with all of them. static
can not be applied to class definitions but can be used for class properties.
UPDATE
modifiers are allowed for class constants since PHP 7.1.0.
class Foo { public const bar = 5; private const baz = 6; }
To summarise,
final static
can not be used to define something like:class X { final static x = 5; }
which is why you have a
const
.
final
is not for class properties, only classes and methods. It means that the method cannot be overridden, or that the class cannot be inherited from. const
is the PHP equivalent to a Java final
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