Vinicius Tavares
Vinicius Tavares

Reputation: 653

Disallow variable overwrite in PHP

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

Answers (5)

Fanda
Fanda

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

Madara's Ghost
Madara's Ghost

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

Nanne
Nanne

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

  1. hide them in a class as private member vars.
  2. expose them through getters.

If needed, make them static

Upvotes: 0

Cymbals
Cymbals

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

n8schloss
n8schloss

Reputation: 2781

Take a look at this question. Also the information about constants in the PHP manual may be helpful.

Upvotes: 7

Related Questions