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 :
final $finalVar = 'extremely secret number'; // don't change
$finalVar = 'hacked...'; // THROW I GIANT BIG ERROR HERE !
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 private
variable
class ParentC {
private $var = 'bob';
}
class ChildC extends ParentC {
public function setVar() {
// Fatal error: Uncaught Error: Cannot access private property ParentC::$var
echo parent::$var;
}
}
Note that there's a hacky way around that using the Reflection class. But, for the most part, you can't touch a private
parent variable from a child class
You can use constants if you want to create variables which you don't want to be changed:
class MyClass {
const VERSION = '2.1'; // This constant can be view outside the class,
// but its value can't be changed even in this class
function myMethod () {
echo self::VERSION; // Inside class
}
}
or outside the class:
echo MyClass::VERSION;
Functional approach:
define ('VERSION', '2.1');
echo VERSION;
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