我需要创建一个简单的成员字段容器的不可变类.我希望其字段在其构造函数中被实例化一次(这些值应该作为构造函数的参数给出).我希望这些字段是公开的,但是不可改变.我可以使用
Java在每个字段之前使用final关键字.在
PHP中怎么做?
您应该使用__set和__get魔术方法,并将该属性声明为protected或private:
- class Example
- {
- private $value;
- public function __construct()
- {
- $this->value = "test";
- }
- public function __get($key)
- {
- if (property_exists($this,$key)) {
- return $this->{$key};
- } else {
- return null; // or throw an exception
- }
- }
- public function __set($key,$value)
- {
- return; // or throw an exception
- }
- }
用法:
- $example = new Example();
- var_dump($example->value);
- $example->value = "invalid";
- var_dump($example->value);
输出:
- string(4) "test"
- string(4) "test"