php 本身没有类似C# readonly这样的修饰符,应该要通过设计实现了吧
php没有提供这样的功能,不过在面向对象的设计中,可以通过set/get方法实现。
class {
private $a = null;
public function setA($a) {
if (null === $this->a) {
$this->a = $a;
}
}
public function getA() {
return $this->a;
}
}
对于set/get方法,可以用__set/__get这两个魔术函数实现,书写效果可以更佳。
常量不就行了吗?
define(key,value)
Talk is cheap,i will show you the code demo.
Like this:
//1.first snippet
class HelloSomeOne{
const NAME = "PHP技术大全";
//todo something else.
}
//2. second snippet
//not in class body inner
const NAME = "PHP技术大全";
在PHP脚本里可以用define实现,在PHP类里可以用const实现
@有明 正解, 但是只需要实现getter就可以了.
Yii
框架的
Object
就实现了这样的功能.
class Object
{
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter();
} elseif (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
} else {
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
}
/**
* Sets value of an object property.
*
* Do not call this method directly as it is a PHP magic method that
* will be implicitly called when executing `$object->property = $value;`.
* @param string $name the property name or the event name
* @param mixed $value the property value
* @throws UnknownPropertyException if the property is not defined
* @throws InvalidCallException if the property is read-only
* @see __get()
*/
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter($value);
} elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
} else {
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
}
}
只要继承
Object
, 如果属性是只读的, 只需要实现getter, 如果是只写的, 只需要实现setter.
class Test extends Object
{
private $a = 'read-only';
public function getA()
{
return $this->a;
}
}