Reputation: 653
Is it possible to prevent variables from being overwritten in PHP? I am making a system that has some reserved variables and I don't want them to be replaced with something else after a certain point. It is possible? If not, what can I do to approach something close to this?
Some of these vars are instantiated classes so I can't define them as constants.
Upvotes: 4
Views: 5212
Reputation: 3786
Maybe you can implement something like frozen state, and if class is frozen, can't be modified:
class Test
{
private $variable;
private $frozen = false;
public function freeze() {
$this->frozen = true;
}
public function setVariable($value) {
if ($this->frozen)
throw new Exception("...");
$this->variable = $value;
}
}
Upvotes: 0
Reputation: 174957
Yes, they're called constants.
If you cannot use them, assuming you're running the latest PHP version, you can use namespaces, using namespaces, you can have 2 variables of the same name, on different namespaces. So that you don't have collisions.
Upvotes: 5
Reputation: 64399
It's impossible to find out how it is the easiest in your situations, as there is no code available at all, but on of the better options would probably be is
If needed, make them static
Upvotes: 0
Reputation: 1174
The best you can do (that I am aware of) in this case is make them private variables inside the class. Then you have to use getters and setters to assign the values, or a construct. That way, someone else's code is less likely to collide with yours.
Upvotes: 3