I can't find out, or maybe I am thinking wrongly but I need to make a variable that can't be changed, like read-only, something like : Show
asked Dec 29, 2016 at 14:16
vdegennevdegenne 10.8k14 gold badges75 silver badges101 bronze badges 9 Aside from constants (as mentioned in comments), the only way I can think of to do this is to use a parent-child relationship with a
Note that there's a hacky way around that using the Reflection class. But, for the most part, you can't touch a
answered Dec 29, 2016 at 14:36
Machavity♦Machavity 30.1k26 gold badges87 silver badges98 bronze badges 2 You can use constants if you want to create variables which you don't want to be changed:
or outside the class:
Functional approach:
answered Aug 3, 2019 at 15:03
AcunaAcuna 1,58715 silver badges19 bronze badges While there has been talk of read-only variables since at least 2012, with even an RFC proposing it on objects, the support does not exist in the language. One way to achieve a read-only variable (or a collection of read-only variables, as might be important with certain configuration values) is with a mediating container:
Which allows you to create a container of read-only variables:
answered Dec 29, 2016 at 14:40
bishopbishop 35.4k10 gold badges99 silver badges133 bronze badges 3 Use constant:
Documentation: define defined
Blaztix 1,1651 gold badge18 silver badges28 bronze badges answered Feb 19, 2019 at 11:43
0 With PHP 8.1 you can now declare a variable as readonly :
Note that you can only apply readonly to typed properties. answered Nov 26, 2021 at 9:50
grunkgrunk 14.3k14 gold badges65 silver badges107 bronze badges Not the answer you're looking for? Browse other questions tagged php final php-7 or ask your own question.What is final variable PHP?The final keyword is used to prevent a class from being inherited and to prevent inherited method from being overridden.
How do you declare a final variable?There are three ways to initialize a final variable:. You can initialize a final variable when it is declared. This approach is the most common. ... . A blank final variable can be initialized inside an instance-initializer block or inside the constructor. ... . A blank final static variable can be initialized inside a static block.. How a variable is declared in PHP?A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
How do you call a final class method in PHP?The final keyword prevents child classes from overriding a method or constant by prefixing the definition with final . If the class itself is being defined final then it cannot be extended. Note: Properties cannot be declared final: only classes, methods, and constants (as of PHP 8.1. 0) may be declared as final.
|