Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to disable adding properties into a class from an instance of the class?

Is there a way to disable adding properties into a class from an instance of the class.

What I mean is this:

Consider this class:

class a {
 private $v1;
 public $v2;

 function func(){
 ...
 }
}

If I do this:

$ins = new a;
$ins->temp = "A variable created from outside the class! C*ap!";
var_dump($ins);

The output:

object(a)#1 (3) {
  ["v1":"a":private]=>
  NULL
  ["v2"]=>
  NULL
  ["temp"]=>
  string(48) "A variable created from outside the class! C*ap!"
}

Can this be disabled?`

like image 241
ThinkingMonkey Avatar asked Dec 25 '11 19:12

ThinkingMonkey


1 Answers

Perhaps you can implement __set() and throw an exception from there:

class a {
    private $v1;
    public $v2;

    public function __set($name, $value) {
        throw new Exception("Cannot add new property \$$name to instance of " . __CLASS__);
    }
}
like image 159
BoltClock Avatar answered Oct 20 '22 01:10

BoltClock