PHP中如何实现只读成员变量?
-
23-09-2019 - |
题
当尝试更改它时,抛出异常。
解决方案
我想对于类属性的解决方案是:
- 不使用您感兴趣的名称定义属性
- 使用魔法
__get
使用“假”名称访问该属性的方法 - 定义
__set
方法,因此在尝试设置该属性时会引发异常。 - 看 超载, ,了解有关魔法方法的更多信息。
对于变量,我认为不可能有一个只读变量,当您尝试写入它时 PHP 会抛出异常。
例如,考虑这个小类:
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
}
}
}
实例化类并尝试读取属性:
$a = new MyClass();
echo $a->myVar . '<br />';
将为您提供预期的输出:
test
在尝试写入该属性时:
$a->myVar = 10;
会给你一个例外:
Exception: not allowed : myVar in /.../temp.php on line 19
其他提示
class test {
const CANT_CHANGE_ME = 1;
}
和你指它作为test::CANT_CHANGE_ME
使用的常数。关键字const
我知道这是一个老问题,但PASCAL的回答真是帮了我,我想给它添加了一点。
__的get()触发不仅对不存在的特性,但“不可访问”个为好,例如受保护的。这使得它容易使只读属性!
class MyClass {
protected $this;
protected $that;
protected $theOther;
public function __get( $name ) {
if ( isset( $this->$name ) ) {
return $this->$name;
} else {
throw new Exception( "Call to nonexistent '$name' property of MyClass class" );
return false;
}
}
public function __set( $name ) {
if ( isset( $this->$name ) ) {
throw new Exception( "Tried to set nonexistent '$name' property of MyClass class" );
return false;
} else {
throw new Exception( "Tried to set read-only '$name' property of MyClass class" );
return false;
}
}
}
简单的回答是不能在PHP创建只读对象的成员变量。
事实上,大部分面向对象语言认为穷人的形式暴露成员变量公开反正...(C#是天大的,丑陋异常,其财产构造)。
如果你想要一个类变量,使用const
关键字:
class MyClass {
public const myVariable = 'x';
}
此变量可被访问:
echo MyClass::myVariable;
这个变量将存在于只有一个版本,无论你创建类型MyClass
有多少不同的对象,并且在大多数面向对象的场景中它几乎没有使用。
然而,如果你想只读变量,其具有每个对象不同的值,则应该使用一个私有成员变量和存取方法(A K的吸气剂):
class MyClass {
private $myVariable;
public function getMyVariable() {
return $this->myVariable;
}
public function __construct($myVar) {
$this->myVariable = $myVar;
}
}
在变量被设置在构造函数,并且它是由不具有设定器制成只读。但MyClass
的每个实例可具有用于myVariable
它自己的值。
$a = new MyClass(1);
$b = new MyClass(2);
echo $a->getMyVariable(); // 1
echo $b->getMyVariable(); // 2
$a->setMyVariable(3); // causes an error - the method doesn't exist
$a->myVariable = 3; // also error - the variable is private
不隶属于 StackOverflow