如何在php中创建对象数组

时间:2013-11-24 12:02:37

标签: php arrays oop object

我正在尝试在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');


?>

尝试创建数组的类不能编译,但只是对如何执行此操作的最佳猜测。再次感谢

2 个答案:

答案 0 :(得分:18)

你应该做的是:

$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'); 

请注意,我正确地将类,对象和函数名称大写。用小写字写下所有东西都不算好。

作为旁注,为什么你的价格是一个字符串?如果你想用它进行适当的计算,它应该是一个数字。

答案 1 :(得分:0)

您可以通过将对象数组编码为json并使用$ assoc标志在json_decode()函数中将其解码为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
    )

)