php 想实现一个字段被赋值后就不能修改了,这样怎么实现呢?
ringa_lee
ringa_lee 2017-04-11 10:29:19
[PHP讨论组]

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

ringa_lee
ringa_lee

ringa_lee

全部回复(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)

PHP中文网

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

在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;
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号