1

I am trying to create a php object that has the following layer.

$obj->property->name;
$obj->property->title;
$obj->property->id;
$obj->property->height;

It give me 'Trying to get property of non-object' error

My object

$obj = [
   'property' => [
       'name' => 'Rick',
       'title' => 'manager',
       'id' => '123',
       'height' => '5.6'
   ]
];

 $obj = = (object)$obj;

I am not sure the correct syntax to produce $obj->property->name;Can anyone help me out? My brain is fired....Thanks!

2
  • $obj is declared as an array, you could just cast (object) on declaration Commented Mar 10, 2016 at 6:04
  • this should be $obj->property['name']; Commented Mar 10, 2016 at 6:15

2 Answers 2

2

You should cast to object also property:

$obj = [
   'property' => [
       'name' => 'Rick',
       'title' => 'manager',
       'id' => '123',
       'height' => '5.6'
   ]
];

$object = (object)$obj;
$object->property = (object)$object->property;

Result:

var_dump($object->property->id); // string(3) "123"
var_dump($object->property->name); // string(4) "Rick"
// etc.
Sign up to request clarification or add additional context in comments.

Comments

1

You have an array inside the property object you can not use like that

$obj->property->name;

This should be:

$obj->property['name'];

Example:

$yourArr = array('property'=>array(
       'name' => 'Rick',
       'title' => 'manager',
       'id' => '123',
       'height' => '5.6'
   ));

$yourObj = (object) $yourArr;
echo $yourObj->property['name']; // Rick

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.