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:
$example = new Example();
var_dump($example->value);
$example->value = "invalid";
var_dump($example->value);
Outputs:
string(4) "test"
string(4) "test"
@property-read
should help your IDE acknowledge existence of this magic property.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…