getter\setter方法來設置讀取內容和賦值內容

getter和setter方法以get、set開頭,後面跟的就是屬性的名字,如getLabelphp

定義好方法後,就能夠像普通屬性同樣使用。可是有本質區別:當這種屬性被讀取是,對應的getter方法被調用,當屬性被賦值時,對應的setter方法被調用。this

使用的時候只需寫屬性名(小寫)getLabel 只須要寫後面的小寫 label。spa

語法:注意若是要賦值的話首先要給類定義一個私有$_label屬性code

private $_label//定義一個屬性

public function getLabel()
    {
        return $this->label;
    }

public function setLabel()
    {
        $this->_label=trim($value);
    }

使用場景,如截取字符串輸出ip

在視圖層裏:utf-8

'columns' => [
            
            //'content:ntext',
            //經過Comment的getter設置,顯示前20個字符
            [
                'attribute'=>'content',
                'value'=>'begining',
            ],
]

在模型類Comment裏:字符串

/**
     * 截取評論內容前20個字符
     */
    public function getBegining()
    {
        $str=strip_tags($this->content);//strip_tags方法從字符串中去除 HTML 和 PHP 標記
        $strLength=mb_strlen($this->content);//mb_strlen獲取字符串的長度

        return mb_substr($str,0,20,'utf-8').(($strLength>=20?'...':''));//mb_substr方法獲取部分字符串
    }
相關文章
相關標籤/搜索