有没有办法禁止从类的实例向类中添加属性?

时间:2011-12-25 19:20:59

标签: php oop properties

是否有办法禁止从类的实例中将properties添加到类中。

我的意思是:

考虑这个课程:

class a {
 private $v1;
 public $v2;

 function func(){
 ...
 }
}

如果我这样做:

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

输出:

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? `

1 个答案:

答案 0 :(得分:19)

也许您可以实现__set()并从那里抛出异常:

class a {
    private $v1;
    public $v2;

    public function __set($name, $value) {
        throw new Exception("Cannot add new property \$$name to instance of " . __CLASS__);
    }
}