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

2022-08-31 00:59:15

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

我的意思是:

请考虑以下类:

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

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

class a {
    private $v1;
    public $v2;

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

答案 2

推荐