Fix Cannot use object of type stdClass as array(PHP)

You are getting this error because you trying to access an object property, using the array square bracket or the object property is of the form 'user name' or 'user-name'.

Normally when we want to access an object in php, we make use of the arrow pointer like

$obj_user = new stdClass;
$obj_user->name = "smith john";
$obj_user->username = "smith";
$obj_user->id = "1002";
$obj_user->email = "smith@nomail.com";

But when you try to access an object as

obj_user['name']

OR

obj_user['my name']

This will throw the "Cannot use object of type stdClass as array"

Fixing the error

Cast the object to an array

$obj_user = new stdClass;
$obj_user->name = "smith john";
$obj_user->username = "smith";
$obj_user->id = "1002";
$obj_user->email = "smith@nomail.com";

//Casting the object to an array 
$obj_user = (array)  $obj_user;

echo $obj_user['name']; //smith john

Accessing the data with {}

$obj_user = new stdClass;
$obj_user->name = "smith john";
$obj_user->username = "smith";
$obj_user->id = "1002";
$obj_user->email = "smith@nomail.com";

//Accessing with curly bracket
echo $obj_user->{'name'};

If you find this helpful, kindly drop a comment or an emoji, cheers.

No Comments Yet