problem create object

Drummer

New member
Hello


I want to create and initialize an object with the following structure :

$Reg->Name =" ";
$Reg->Last name1=" ";
$Reg->Last name2=" ";

for ($i=0; $i<14; $i++)
{
$Reg->$dwelling[$i]->propiety =" ";
$Reg->$dwelling[$i]->Rent = " ";
}

I have tried

$Reg = new stdClass();

Initializes without problems :

$Reg->Name =" ";
$Reg->Last name1=" ";
$Reg->Last name2=" ";

But it gives an error with :

$Reg->$dwelling[0]->propiety =" ";
$Reg->$dwelling[0]->Rent = " ";

$Reg->$dwelling[1]->propiety =" ";
$Reg->$dwelling[1]->Rent = " ";
..............

Any ideas thanks.
 
The issue you are encountering is related to how you are trying to access and initialize the $dwelling array within the stdClass object. In PHP, you cannot directly use the array syntax with object properties in the way you've shown.

PHP:
$Reg = new stdClass();

// Initialize basic properties
$Reg->Name = " ";
$Reg->{"Last name1"} = " ";
$Reg->{"Last name2"} = " ";

// Initialize the dwelling properties
$Reg->dwelling = array(); // Initialize dwelling as an empty array

for ($i = 0; $i < 14; $i++) {
    $Reg->dwelling[$i] = new stdClass(); // Initialize each element as an stdClass object
    $Reg->dwelling[$i]->propiety = " ";
    $Reg->dwelling[$i]->Rent = " ";
}

  1. Basic Properties:

    PHP:
    $Reg->Name = " ";
    $Reg->{"Last name1"} = " ";
    $Reg->{"Last name2"} = " ";
    Here, we are setting basic properties of the $Reg object. Note that for properties with spaces in their names, we use curly braces to properly set them.
  2. Dwelling Properties:

    PHP:
    $Reg->dwelling = array();
    We initialize dwelling as an empty array.

    PHP:
    for ($i = 0; $i < 14; $i++) {
    $Reg->dwelling[$i] = new stdClass(); // Create a new stdClass object for each dwelling
    $Reg->dwelling[$i]->propiety = " ";
    $Reg->dwelling[$i]->Rent = " ";
    }
    Inside the loop, we create a new stdClass object for each element of the dwelling array and then set the propiety and Rent properties for each dwelling.
This approach ensures that each dwelling element is an object with its own properties, and the code should work without any errors.

Best Regard
Danish Hafeez | QA Assistant
ICTInnovations
 
You have no problem with the code like this?:
$Reg->Last name2=" ";

You need to learn about classes, you do not need stdClass
 
Back
Top