How to create an array of objects in php

I am trying to create an array of objects in php, and I was curious how I would do it. Any help would be great, thanks!

Here is the class that will be contained in the array

<?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; } } 

And here is what I'm trying to do -

 <?PHP include 'file.php'; $hotelsdetail=array(); $hotelsdetail[0]=new hoteldetails(); $hotelsdetail[0].sethotelinfo($rs); $hotelsdetail[0].setprice('150'); ?> 

A class trying to create an array does not compile, but is the best guess as to how I can do this. Thanks again

+6
source share
3 answers

You should probably do the following:

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

In your particular case, the problem is that you should use -> , not . . This period is not used in PHP to access class attributes or methods:

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

Please note that I have correctly described the names of classes, objects, and functions. Writing everything in lower case is not considered a good style.

As a side note, why is your price a string? It really should be a number if you ever want to make the right calculations with it.

+17
source

You should add to your array, and not assign a null index.

 $hotelsdetail = array(); $hotelsdetail[] = new hoteldetails(); 

This will add the object to the end of the array.

 $hotelsdetail = array(); $hotelsdetail[] = new hoteldetails(); $hotelsdetail[] = new hoteldetails(); $hotelsdetail[] = new hoteldetails(); 

This will create an array with three objects, each of which will add each.


In addition, to properly access the properties of objects, you must use the -> operator.

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

You can get an array of an object by encoding it in json and decoding it with the $ assoc flag as FALSE in the json_decode () function.

See the following example:

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

It will display an array of objects.

output:

 Array ( [0] => stdClass Object ( [attach_id] => test ) [1] => stdClass Object ( [attach_id] => test1 ) [2] => stdClass Object ( [attach_id] => test2 ) ) 
0
source

Source: https://habr.com/ru/post/958720/


All Articles