duanke0178 2013-12-19 16: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 16: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.

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

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算