Nikola R.
Nikola R.

Reputation: 1173

Protecting stand-alone variables

Is it possible to protect defined variable from overriding (changing value)? I am making an system which uses plugins and I want to prevent plugin writer (myself) from changing some of specific defined variables (objects that holds new class instances).

Something like this:

Class Foo { 
  function __construct() {
    return "Hello";
  }
}
$bar= new Foo();

So later, I will be using global $bar; in my functions but I don't want to allow changing that variable like this:

$bar = new Foo(); $bar = "New value";

$bar must always stay the same (new Foo()) since it is going to be a big system and I cannot remember hundreds of core variables I defined.

Ideally would be, if I try to redefine it - php should throw fatal error. Is there a such thing?

Upvotes: 2

Views: 119

Answers (2)

Martin Konecny
Martin Konecny

Reputation: 59651

Why is your constructor returning a string? By definition a constructor returns a reference to an object.

If you just want a a reference to a string that cannot change, why not just make a const?

const STRING_THAT_WONT_CHANGE = 'foo';

Upvotes: 0

d.raev
d.raev

Reputation: 9546

This sounds like Singleton pattern:

class Foo
{
    protected static $instance = null;
    protected function __construct()
    {
        throw new Exception('use ::getInstance()');
    } 

    public static function getInstance()
    {
        if (!isset(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }
}

use:

$bar = Foo::getInstance();

any one can redeclare $bar .. but if they wont the real Foo ... they need to get the instance;

Upvotes: 2

Related Questions