Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm attempting to create an array of objects in php and was curious how I would go about that. 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 am attempting to do-

<?PHP
include 'file.php';

$hotelsdetail=array();    

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


?>

The class attempting to create the array doesn't compile but is just a best guess as to how I can do this. Thanks again

share|improve this question
2  
Use $hotelsdetail[0]->sethotelinfo($rs); and $hotelsdetail[0]->setprice('150'); –  haim770 Nov 24 '13 at 12:04
1  
add this in the beginning of your script to get the exact error: error_reporting(E_ALL|E_STRICT); ini_set('display_errors', true); –  Matthew Nov 24 '13 at 12:04

1 Answer 1

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

Use ->, not .. The period isn't used in PHP to access attributes or methods of a class.

Also, you should capitalize your classes and functions properly, e.g.

  • class hoteldetails should be class HotelDetails
  • sethotelinfo should be setHotelInfo
  • etc.

Have a look at the Zend framework naming conventions or the PEAR standards to get a few ideas.

Perhaps it would be easier to write it like this:

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

And finally, why is your price a string? It should be a number, really, if you ever want to do proper calculations with it.

share|improve this answer
    
Thanks, this was just something I free handed really quick to explain my problem which is why some of it looks sloppy. –  Alex Miles Nov 24 '13 at 12:18
    
Thanks for this. It helped me. If it worked for @AlexMiles Miles then he should mark it as answer! :) –  Nirav Zaveri Jul 9 at 9:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.