php 想实现一个字段被赋值后就不能修改了,这样怎么实现呢?
ringa_lee
ringa_lee 2017-04-11 10:29:19
0
5
228

php 本身没有类似C# readonly这样的修饰符,应该要通过设计实现了吧

ringa_lee
ringa_lee

ringa_lee

reply all(5)
大家讲道理

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)

Ty80

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技术大全";
PHPzhong

在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;
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!