[英]PHP constant member variable
I'm looking for a way to declare a member variable that cannot change once initialized (it can be set once, but never reset). 我正在寻找一种声明成员变量的方法,该成员变量一旦初始化就无法更改(它只能设置一次,但永远不会重置)。
I am not looking for a class constant but a per-instance member variable. 我不是在寻找类常量,而是在每个实例的成员变量。 Is there anyway to do this in PHP? 反正有用PHP执行此操作吗?
A solution can be: 解决方案可以是:
class SuperClass {
private $_something;
public final SetSomething(SomethingCls $something) {
if ($this->_something != NULL) {
throw new \Exception();
}
$this->_something = $something;
}
public final GetSomething() {
return $this->_something;
}
}
The fact is there isn't any PHP construct to achive this so you have to write your own implementation to solve the specific problem. 事实是,没有任何PHP构造可实现此目的,因此您必须编写自己的实现来解决特定问题。 You can not protect a variable from overwriting without having some checking and/or protecting by inheritance. 如果没有进行继承的检查和/或保护,就无法保护变量不被覆盖。
您可以使用final关键字:-
final $variable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.