如何在php中创建对象数组
我正试图用php创建一个对象数组,我很好奇我会怎么做。任何帮助都会很好,谢谢 下面是将包含在数组中的类如何在php中创建对象数组,php,arrays,oop,object,Php,Arrays,Oop,Object,我正试图用php创建一个对象数组,我很好奇我会怎么做。任何帮助都会很好,谢谢 下面是将包含在数组中的类 <?php class hoteldetails { private $hotelinfo; private $price; public function sethotelinfo($hotelinfo){ $this->hotelinfo=$hotelinfo; } public function setprice($price){ $this->p
<?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;
}
}
试图创建数组的类没有编译,但只是我如何编译的最佳猜测。再次感谢您可能应该做的是:
$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');
请注意,我正确地将类、对象和函数名大写。用小写写每件事都被认为是不好的风格
作为旁注,为什么你们的价格是一个字符串?如果你想用它进行正确的计算,它应该是一个数字。你应该附加到数组中,而不是赋给索引零
$hotelsdetail = array();
$hotelsdetail[] = new hoteldetails();
这将把对象附加到数组的末尾
$hotelsdetail = array();
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();
这将创建一个包含三个对象的数组,并依次附加每个对象
此外,要正确访问对象属性,应使用
->
操作符
$hotelsdetail[0]->sethotelinfo($rs);
$hotelsdetail[0]->setprice('150');
您可以通过将对象数组编码为json并在json_decode()函数中将$assoc flag解码为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
)
)
使用
$hotelsdetail[0]->sethotelinfo($rs)代码>和$hotelsdetail[0]>setprice('150')代码>在脚本的开头添加此代码以获得准确的错误:错误报告(E|u ALL | E|u STRICT);ini设置(“显示错误”,真);谢谢,这是我可以很快解释我的问题的东西,这就是为什么有些东西看起来很邋遢的原因。谢谢。它帮助了我。如果它对@AlexMiles有效,那么他应该将其标记为答案!:)@BryantJackson虽然我同意编码风格是主观的,但我仍然认为应该提到这一点,在这种情况下,OP应该学会大写,而不是用小写来书写。请注意,在堆栈溢出时,不鼓励像您这样的编辑,因为它们会从根本上改变答案。如果——对于这些主观问题——你留下一条评论,OP可以据此决定他们是否(以及如何)改进自己的答案,那就更好了。谢谢
Array
(
[0] => stdClass Object
(
[attach_id] => test
)
[1] => stdClass Object
(
[attach_id] => test1
)
[2] => stdClass Object
(
[attach_id] => test2
)
)