2015-04-17 92 views
0

我有一個數組中的對象。我想訪問這些對象的屬性,但我沒有任何運氣。PHP:無法訪問數組中的對象鍵

class Article { 
    public $category; 
    public $title; 
    public $img; 
    public $location; 
    public $text; 


    public function __construct($category, $title, $img, $location, $text) { 
     $this->category = $category; 
     $this->title = $title; 
     $this->img = $img; 
     $this->location = "pages/" . $location; 
     $this->text = $text; 
    } 
} 

//db of articles 
$runawayFive = new Article("news", "The Runaway Five Comes to Fourside",  "img/BluesBrothers.jpg", 
"runaway_five_comes_to_fourside.html", 
"The Runway Five continues its nationwide tour, stopping in Fourside to perform at the world famous Topolla Theater. Previously, an unexpected delay caused the group to postpone its shows for over a week. The award-winning group was forced to speed ten days in neighboring town, Threed. Tunnels going to and from Threed were blocked, but no one really knows how or why." . "<br>" 
."The Runaway Five will being playing at the Topolla Theater during Friday and Saturday night. Tickets are $20 per adult." 
); 
$articles = Array($runawayFive); 
echo $articles[0]["title"]; 

我應該有文章的標題迴應出來,但我沒有得到任何東西。我可以做var_dump($articles[0])並返回該對象,但無法訪問其值。

回答

2

在PHP中,您可以使用->運算符來訪問對象屬性。

echo $articles[0]->title; 
0

發現您可以直接訪問對象屬性這樣

echo $runawayFive->title; 

無需數組轉換

0
$articles 

這是一個數組,這個數組只有1個值,並且你在arrray中的唯一值是來自類型Article的對象。

array(
    0 => new Article() 
); 

您可以通過鍵引用數組的每個值,默認情況下它的鍵是從零開始的數字索引。所以,你可以通過

$articles[ $indexValue ]; 

訪問數組在這種情況下,你可以有這樣的:

$article = $articles[ 0 ]; 

要訪問該指數爲零的數組的值。所以在這種情況下,這是一個對象。因此,要訪問使用->運算符的對象的非靜態方法或實例變量。就像如下:

$article->title; 

短sintax是:

$articles[0]["title"]; 

而且有着更好的一個:

$article = $articles[0]; 
$article->title; 

對於輸出值在調用實例變量之前只寫echo

像:

$article = $articles[0]; 
echo $article->title; 

OR

echo $articles[0]->title;