zoukankan      html  css  js  c++  java
  • Yii2属性(Property)的学习

    属性在Yii2中是一个比较重要的存在是很多东西存在的基础,比如事件、行为、组件等。在Yii中,由 yiiaseObject 提供了对属性的支持,因此,如果要使你的类支持属性, 必须继承自 yiiaseObject 。Yii中属性是通过PHP的魔法函数 __get() __set() 来产生作用的。 
     

     
    vendor/yiisoft/yii2/base/BaseObject.php
        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);
            }
        }
        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);
            }
    
            throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
        }

    实现属性的步骤

    class Post extends yiiaseBaseObject    // 第一步:继承自 yiiaseBaseObject
    {
        private $_title;                 // 第二步:声明一个私有成员变量
        public function getTitle()       // 第三步:提供getter和setter
        {
            return $this->_title;
        }
        public function setTitle($value)
        {
            $this->_title = trim($value);
        }
    }
  • 相关阅读:
    Nginx 部署多个 web 项目(虚拟主机)
    Nginx 配置文件
    Linux 安装 nginx
    Linux 安装 tomcat
    Linux 安装 Mysql 5.7.23
    Linux 安装 jdk8
    Linux 安装 lrzsz,使用 rz、sz 上传下载文件
    springMVC 拦截器
    spring 事务
    基于Aspectj 注解实现 spring AOP
  • 原文地址:https://www.cnblogs.com/hanpengyu/p/11286904.html
Copyright © 2011-2022 走看看