有没有办法禁止从类的实例向类添加属性? [英] Is there a way to disable adding properties into a class from an instance of the class?

查看:63
本文介绍了有没有办法禁止从类的实例向类添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以禁用将属性添加到来自该类实例的类.

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

我的意思是:

考虑此类:

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

推荐答案

也许您可以实现

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__);
    }
}

这篇关于有没有办法禁止从类的实例向类添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆