PHP 怎麼擷取protected屬性

來源:互聯網
上載者:User
PHP 如何擷取protected屬性?
class userVo extends model {
protected $userid = array(.....);

protected $username = array(.....);

.........
}


class model{

public function getVoProtectedProperties(){

如何擷取userVo(對象而不是類) 內的protected屬性?
$this指向子類執行個體
}
}



class Action {
public function init(){
$uservo = new userVo();
$uservo->getVoProtectedProperties();
}
}

-------------------------
不想使用: $class_date = new ReflectionClass(get_class($this)); 來得到屬性。
能不能直接得到對象的所有protected屬性的欄位的值。

分享到:


------解決方案--------------------

用魔術方法,不知道是不是你想要的
class userVo extends model {
protected $userid = array(.....);

protected $username = array(.....);



private function __get($property_name)
{
if(isset($this->$property_name))
{
return($this->$property_name);
}else
{
return(NULL);
}
}

private function __set($property_name, $value)
{
$this->$property_name = $value;
}

}

------解決方案--------------------
不用反射的話,可以在userVo 類中添加一個方法getProp

public function getProp(){
return get_class_vars(get_class($this));
}

不用反射,在類外是擷取不到protected和private屬性的
------解決方案--------------------
如果不想用反射的話,每個VO類多加個數組,數組的內容就是protected的屬性名稱,直接返回這個數組。

屬性名稱本身就只能靠反射返回,按照編程的思路上來說,屬性名稱應該是具名的,而按照你設計的目的來說,屬性名稱非具名,還要靠一定的邏輯去擷取,這本身是不是存在設計上的缺陷呢?

class userVo extends model {
protected $prote = array(
'userid' => 'id',
'username' => 'username',
);

// 而這個對象中完全可以用$this->prote['userid']來代替$this->userid
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.