Blingue
Blingue

Reputation: 127

create anonymous object in php

include('Property.php');
$obj = new Property ();
$obj->price = 2500.00;
$obj ['address_primary'] = '100 Main St';
$obj->state = 'VA';
echo 'Address :: ', $obj->address_primary, ' ', PHP_EOL;
echo 'City, State, Zip :: ', $obj ['state'];

Can please someone Explain to me how, from having this : $obj = new Property () we can create/initialize or have : $obj ['address_primary'] and be able to echo this : $obj->address_primary

Sorry but I try to explain the problem as much as i could. Thanks for your answers Folks!!

Upvotes: 2

Views: 338

Answers (3)

Varun Bajaj
Varun Bajaj

Reputation: 1043

File 'Property.php'
Add property
$address_primary = "";
$defaultAddress = "This is temp address to test";
funciton __construct($primaryAddress = ""){
  this->address_primary = (strlen(trim($primaryAddress)) > 0)?
  $primaryAddress :$defaultAddress;  
}

Upvotes: 0

hafichuk
hafichuk

Reputation: 10781

You should be able to just change

$obj ['address_primary'] = '100 Main St';

to

$obj->address_primary = '100 Main St';

You'll also have to change

echo 'City, State, Zip :: ', $obj ['state'];

to

echo 'City, State, Zip :: ', $obj->state;

Upvotes: 1

Zevi Sternlicht
Zevi Sternlicht

Reputation: 5399

You are trying to access a property as an array element. You need to extend ArrayObject. http://php.net/manual/en/class.arrayobject.php to do this. Otherwise dont mix objects and arrays.

Upvotes: 1

Related Questions