yii2中getter和setter需要注意哪些

php教程评论139 views阅读模式

本文主要和大家分享yii2中getter和setter需要注意哪些,希望能帮助大家更好掌握yii2中getter和setter的使用方法。

让我们先来看看yiichina中权威指南的描述:

  • 这类属性的名字是不区分大小写的。如,$object->label 和 $object->Label 是同一个属性。 因为 PHP 方法名是不区分大小写的。

  • 如果此类属性名和类成员变量相同,以后者为准。 例如,假设以上 Foo 类有个 label 成员变量, 然后给 $object->label = 'abc' 赋值,将赋给成员变量而不是 setter setLabel() 方法。

  • 这类属性不支持可见性(访问限制)。定义属性的 getter 和 setter 方法是 public、protected 还是 private 对属性的可见性没有任何影响。

  • 这类属性的 getter 和 setter 方法只能定义为非静态的,若定义为静态方法(static)则不会以相同方式处理。

  • 对 property_exists() 不能确定魔术属性的正常调用。你应该调用 canGetProperty() 或 canSetProperty()。

一、先来看看这一条:

如果此类属性名和类成员变量相同,以后者为准。 例如,假设以上 Foo 类有个 label 成员变量, 然后给 $object->label = ‘abc’ 赋值,将赋给成员变量而不是 setter setLabel() 方法。

其实这句话就是说嘛我们的setter和getter只对隐藏属性和受保护属性起作用。如果是public修饰符修饰的变量则直接会赋值和获取,而不会经过我们的setter或者getter,例子:

<?php
/**
 * Created by PhpStorm.
 * Author: weiyongqiang <hayixia606@163.com>
 * Site: www.weiyongqiang.com
 * Date: 2017/3/6
 * Time: 23:29
 */
namespace frontend\components;
use yii\base\Component;
class UserInfo extends Component
{
    public $userid = 11;
    public $userName;
    public function __construct(array $config)
    {
        parent::__construct($config);
    }
    public function setUserId($userId)
    {
        echo 123;
        $this->userId = $userId;
    }
    public function getuserid()
    {
        //return $this->userId;
        return 123456;
    }
}
然后实例化组件后的获取userid属性
$userInfo = new UserInfo([]);echo "<pre/>";
//$userInfo->userId = 10;echo $userInfo->userid;exit;

输出结果为:11

那就说明userid为public修饰符的属性时根本就没有进入我所定义的getuserid,所以如果你的属性时public类型的如果想对属性进行统一的处理就不能用getter来实现了。

本文为魏永强原创作品未经允许不得转载:MarsWill » yii2中getter 和 setter 注意事项。

相关推荐:

Javascript中getter和setter基本介绍

谈谈因Vue.js引发关于getter和setter的思考

ECMAScript5中的对象存取器属性:getter和setter介绍_javascript技巧

以上就是yii2中getter和setter需要注意哪些的详细内容,更多请关注php教程网其它相关文章!

企鹅博客
  • 本文由 发表于 2020年7月6日 02:03:13
  • 转载请务必保留本文链接:https://www.qieseo.com/256410.html

发表评论