Yii2 理解Object

1 版本

// yii\BaseYii\getVersion
public static function getVersion()
{
    return '2.0.10';
}

2 继承与实现

Object实现了Configurable接口。
Configureable要求在构造函数的参数末尾加上$config

public function __constructor($param1, $param2, ..., $config = [])

3 构造函数 __construct

// 按照Configureable要求, 需要在参数末尾添加 $config = []
public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    // 调用了初始化函数
    $this->init();
}

4 __get, __set

// 重写了php5中预定义的__get
// php5中的代码:
public function __get($name)
{ 
    return $this->$name; 
} 
// yii中的代码
public function __get($name)
{
    // 由原来的直接调用属性改为通过调用get函数来间接调用
    $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);
    }
}

同理于__set
在代码中可以看见,如果找不到$getter, 却找到了setter, 就会报出异常,这个属性不可读。

5 method_exists

用于检测类中指定的函数是否存在

6 __isset, __unset

__isset 用于判断某个属性是否定义了
__unset 用于将某个属性设置为null,但是对只读的属性,会报异常

最好不要直接使用__isset和__unset,而是使用isset和unset

public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) 
    {
        return $this->$getter() !== null;
    } 
    else 
    {
        return false;
    }
}
public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) 
    {
        $this->$setter(null);
    } 
    elseif (method_exists($this, 'get' . $name)) 
    {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

7 其余判断函数

以下函数基本上借助于method_exists和property_exists

hasProperty
canGetProperty
canSetProperty
hasMethod
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值