PHP:不可变的公共成员字段 [英] PHP: immutable public member fields
问题描述
我需要创建一个不可变的类,它只是一个成员字段容器.我希望它的字段在其构造函数中实例化一次(值应作为构造函数的参数提供).我希望这些领域公开,但一成不变.我可以在每个字段之前使用final
关键字使用Java完成此操作.如何在PHP中完成?
I need to create an immutable class which is simply a member field container. I want its fields to be instantiated once in its constructor (the values should be given as parameters to the constructor). I want the fields to be public but immutable. I could have done it with Java using the final
keyword before each field. How is it done in PHP?
推荐答案
您应该使用__set
和__get
魔术方法,并将该属性声明为protected或private:
You should use __set
and __get
magic methods and declare that property as protected or private:
/**
* @property-read string $value
*/
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"
@property-read
应该可以帮助您的IDE确认存在神奇的财产.
@property-read
should help your IDE acknowledge existence of this magic property.
这篇关于PHP:不可变的公共成员字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!