如何在PHP中实现只读成员变量? [英] How to implement a read-only member variable in PHP?
本文介绍了如何在PHP中实现只读成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试更改它时,引发异常.
When trying to change it,throw an exception.
推荐答案
对于类属性,我想一个解决方案是:
I suppose a solution, for class properties, would be to :
- 不使用您感兴趣的名称定义属性
- 使用神奇的
__get
方法,使用假"名称访问该属性 - 定义
__set
方法,以便在尝试设置该属性时抛出异常. - 有关魔术方法的更多信息,请参见重载. li>
- not define a property with the name that interests you
- use the magic
__get
method to access that property, using the "fake" name - define the
__set
method so it throws an exception when trying to set that property. - See Overloading, for more informations on magic methods.
对于变量,我认为不可能有一个只读变量,当您尝试向其写入数据时,PHP会对该变量抛出异常.
For variables, I don't think it's possible to have a read-only variable for which PHP will throw an exception when you're trying to write to it.
例如,考虑这个小类:
For instance, consider this little class :
class MyClass {
protected $_data = array(
'myVar' => 'test'
);
public function __get($name) {
if (isset($this->_data[$name])) {
return $this->_data[$name];
} else {
// non-existant property
// => up to you to decide what to do
}
}
public function __set($name, $value) {
if ($name === 'myVar') {
throw new Exception("not allowed : $name");
} else {
// => up to you to decide what to do
}
}
}
实例化该类并尝试读取该属性:
Instanciating the class and trying to read the property :
$a = new MyClass();
echo $a->myVar . '<br />';
将为您带来预期的输出:
Will get you the expected output :
test
在尝试写入属性时:
$a->myVar = 10;
会给你一个例外:
Exception: not allowed : myVar in /.../temp.php on line 19
这篇关于如何在PHP中实现只读成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文