Keith Ivison
Keith Ivison

Reputation: 407

Creating dynamically named objects

I am integrating with an API and need to create objects to submit to the API server.

I could write the following

$objBedroom1 = $objRequest->property->details->rooms()->create();
$objBedroom1->room_name = "Bedroom1";
print_r($objBedroom1) ;

$objBedroom2 = $objRequest->property->details->rooms()->create();
$objBedroom2->room_name = "Bedroom2";
print_r($objBedroom2) ;

etc but teh bedrooms are not always set to 3, they could be anything up to 5 so I want to be able to iterate through the # of bedrooms and create an object for each but the issue is if I try the following...

$bedz = 3;//or set by the database variable as an int

for ($i=0; $i < $bedz; $i++) { 
    $objBedroom.$i = $objRequest->property->details->rooms()->create();
    $objBedroom.$i->room_name = "Bedroom.$i";
    print_r($objBedroom.$i) ;
}

The php error Undefined variable: objBedroom comes back

It would seem that I cant create a $objBedroom plus a variable number.

Any help appreciated

Regards Keith

An old dog trying to learn new tricks!

Upvotes: 0

Views: 31

Answers (2)

dimlucas
dimlucas

Reputation: 5131

For your code to work, $objBedroom needs to be an array. The proper array syntax to access the ith element is

$objBedroom[$i]

not

$objBedroom.$i

The second syntax is, first invalid because there is a dollar sign after the dot operator, but also tells PHP to treat $objBedroom as if it is an object, not an array. The code fails because when accessing a field of an object using the dot operator (.) the variable must reference an object.

For an array to work, you can declare it like this:

$objBedroom = array();

But that's not necessary, it's just nice to have to make your code more easily understandable.

To solve your problem just change your code to use proper array syntax and you'll be fine:

$bedz = 3;//or set by the database variable as an int

for ($i=0; $i < $bedz; $i++) { 
    $objBedroom[] = $objRequest->property->details->rooms()->create();
    $objBedroom[$i]->room_name = "Bedroom.$i";
    print_r($objBedroom[$i]) ;
}

Notice this syntax:

$objBedroom[] = $objRequest->property->details->rooms()->create();

You don't explicitly specify an index. This tells PHP to push the room in the array so the first room will be placed in $objBedroom[0] , the second in $objBedroom[1], e.t.c automatically

Upvotes: 1

Use array instead of dynamic variable names.

$bedrooms = array(); // or $bedrooms = []; for PHP v5.4+
$bedz = 3; // or set by the database variable as an int

for ($i = 0; $i < $bedz; $i++) { 
    $bedroom = $objRequest->property->details->rooms()->create();
    $bedroom->room_name = "Bedroom." + $i;

    $bedrooms[] = $bedroom; // append new bedroom
}

var_dump($bedrooms);

Upvotes: 0

Related Questions