duanke0178 2013-12-19 08:11
浏览 51
已采纳

PHP OOP无法设置私有属性

I have a class UserFavorite that extends User. When i create new object with the class constructor setters cannot set properties.

Constructor:

public function __construct($username, $tabId, $favName, $favUrl = null, $favPosition = null, $favComment = null) {
    parent::__construct($username);
    $this->tabId = $this->setTabId($tabId);
    $this->favName = $this->setFavName($favName);
    $this->favUrl = $this->setFavUrl($favUrl);
    $this->favPosition = $this->setFavPosition($favPosition);
    if ($favComment) {
        $this->favComment = $this->setFavComment($favComment); 
    }
}

Setter:

public function setFavUrl($favUrl) {
        $url = filter_var($favUrl, FILTER_VALIDATE_URL);
        if (!$url) {
            echo $this->showError(...);
            exit;
        }
        echo $url; // THIS LOGS THE URL
        $this->favUrl = $url;
    }

I creatirng new instance $fav = new UserFavorite($user->getUsername(), 1, 'favorite', 'http://abv.bg', 5, 'mamatisiebalo' );

And when i print $fav i receive :

favorite<pre>UserFavorite Object
(
    [favName:UserFavorite:private] => 
    [tabId:UserFavorite:private] => 
    [favUrl:UserFavorite:private] => 
    [favPosition:UserFavorite:private] => 
    [favComment:UserFavorite:private] => 
    [_favId:UserFavorite:private] => 
    [username:protected] => myUserName
    [_userId:protected] => 1
)

Any ideas?

展开全部

  • 写回答

1条回答 默认 最新

  • dongxi0605 2013-12-19 08:13
    关注

    You are setting $this->favUrl in the setter function, then overwritting it by assigning the result of the setter function to the same variable.

    If you change

    $this->favUrl = $this->setFavUrl($favUrl);
    

    To

    $this->setFavUrl($favUrl);
    

    You should be OK.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部