2013-12-19 55 views
1

我有一個UserFavorite類擴展了用戶。 當我用類構造函數創建新對象setter無法設置屬性。PHP OOP無法設置私有屬性

構造:

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

二傳手:

​​

我creatirng新實例$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 
) 

任何想法?

+2

如果這些屬性是'User'類中的私有屬性,那麼您無法從'UserFavourites'類中訪問它們....這就是'private'意味着什麼 –

+1

'$ this-> tabId = $ this- > setTabId($ tabId);'你爲什麼手動設置它並調用setter?它應該是'$ this-> setTabId($ tabId);'或'$ this-> tabId = $ tabId;' – Jessica

+1

+1 Mark Ba​​ker所說的。如果你正在擴展這個類,並且想要訪問父變量,使用'protected'而不是'private'。 – Crackertastic

回答

5

您正在設置函數中設置$this->favUrl,然後通過將setter函數的結果賦值給同一個變量來覆蓋它。

如果更改

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

$this->setFavUrl($favUrl); 

你應該沒問題。