PHP OOP无法设置私有属性

时间:2013-12-19 16:11:05

标签: php oop setter

我有一个扩展用户的UserFavorite类。 当我使用类构造函数创建新对象时,setters无法设置属性。

构造函数:

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); 
    }
}

设置器:

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;
    }

我创建了新实例$fav = new UserFavorite($user->getUsername(), 1, 'favorite', 'http://abv.bg', 5, 'mamatisiebalo' );

当我打印$fav时,我会收到:

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
)

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

您在setter函数中设置$this->favUrl,然后通过将setter函数的结果赋值给同一变量来覆盖它。

如果你改变了

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

$this->setFavUrl($favUrl);

你应该没事。