PHP:无法访问数组中的对象键

时间:2015-04-17 00:24:14

标签: php arrays object

我在数组中有对象。我想访问这些对象'物业,但我没有运气。

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])并返回该对象,但无法访问其值。

5 个答案:

答案 0 :(得分:2)

在PHP中,您可以使用->运算符访问对象属性。

echo $articles[0]->title;

答案 1 :(得分:0)

试试这个

echo $articles[0]->title;

可在此处找到更多信息和示例http://php.net/manual/en/language.types.object.php

答案 2 :(得分:0)

您可以像这样直接访问对象属性

echo $runawayFive->title;

无需数组转换

答案 3 :(得分: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;

答案 4 :(得分:0)

是的,您必须访问以下属性:

$articles[0]->title;

或者,如果您真的想要以数组格式访问属性,则可以实现“ArrayAccess”#39;如下所示:

class Article implements ArrayAccess {

 public $title;

}

$article = new Article();
echo $article['title'];

供参考:

http://php.net/manual/en/class.arrayaccess.php http://php.net/manual/en/language.oop5.interfaces.php