如何在PHP中创建对象数组

8
我想创建一个php对象数组,不知道如何操作。希望能得到帮助,非常感谢!
以下是将包含在数组中的类:
<?php

class hoteldetails {
private $hotelinfo;
private $price;

public function sethotelinfo($hotelinfo){
    $this->hotelinfo=$hotelinfo;
}

public function setprice($price){
    $this->price=$price;
}

public function gethotelinfo(){
    return $hotelinfo;
}

public function getprice(){
    return $price;
}

}

这是我尝试要做的事情:

<?PHP
include 'file.php';

$hotelsdetail=array();    

$hotelsdetail[0]=new hoteldetails();
$hotelsdetail[0].sethotelinfo($rs);
$hotelsdetail[0].setprice('150');


?>

尝试创建数组的类并不能编译,但只是我能够做到这一点的最好猜测。再次感谢。


3
请使用"$hotelsdetail[0]->sethotelinfo($rs);"和"$hotelsdetail[0]->setprice('150');"。请注意,不要改变原意。 - haim770
2
在你的脚本开头添加以下内容以获取精确的错误信息: error_reporting(E_ALL|E_STRICT); ini_set('display_errors', true); - Matthew
3个回答

20
你应该做的是:
$hotelsDetail = array();

$details = new HotelDetails();
$details->setHotelInfo($rs);
$details->setPrice('150');

// assign it to the array here; you don't need the [0] index then
$hotelsDetail[] = $details;

在您的特定情况下,问题是您应该使用->而不是.。在PHP中,句号不用于访问类的属性或方法:

$hotelsdetail[0] = new hoteldetails();
$hotelsdetail[0]->sethotelinfo($rs);
$hotelsdetail[0]->setprice('150'); 

请注意,我正确地大写了类、对象和函数名称。全部使用小写不被认为是良好的风格。
顺便说一下,你的价格为什么是一个字符串?如果你想进行正确的计算,它应该是一个数字。

谢谢,这只是我随手写的一些东西,为了解释我的问题,所以有些看起来有点潦草。 - Alex Miles
谢谢你的帮助,对我很有用。如果@AlexMiles也有效的话,他应该把它标记为答案! :) - Nirav Zaveri
@BryantJackson 虽然我同意编码风格是主观的,但我仍然认为应该提到它,而在这种情况下,OP 应该学会大写字母,而不是全部小写。请注意,像你这样彻底改变答案的编辑在 Stack Overflow 上是不被鼓励的。如果针对这种主观问题,你留下了评论,那么 OP 就可以决定是否以及如何改进他们的答案。谢谢! - slhck

2
你应该将数据追加到数组中,而不是赋值给索引零。
$hotelsdetail = array();    
$hotelsdetail[] = new hoteldetails();

这将把对象添加到数组的末尾。
$hotelsdetail = array();    
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();

这将创建一个包含三个对象的数组,并依次添加每个对象。


此外,为了正确访问对象的属性,您应该使用->运算符。

$hotelsdetail[0]->sethotelinfo($rs);
$hotelsdetail[0]->setprice('150');

0

您可以通过将其编码为 JSON 并在 json_decode() 函数中使用 $assoc 标志为 FALSE 来获取对象数组。

请参见以下示例:

    $attachment_ids = array();
    $attachment_ids[0]['attach_id'] = 'test';
    $attachment_ids[1]['attach_id'] = 'test1';
    $attachment_ids[2]['attach_id'] = 'test2';
    $attachment_ids                 = json_encode($attachment_ids);
    $attachment_ids                 = json_decode($attachment_ids, FALSE);
    print_r($attachment_ids);

它将呈现一个对象数组。

输出:

Array
(
[0] => stdClass Object
    (
        [attach_id] => test
    )

[1] => stdClass Object
    (
        [attach_id] => test1
    )

[2] => stdClass Object
    (
        [attach_id] => test2
    )

)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接