How many times have you fallen upon the dreaded “cannot use object of type stdClass as array” error message? In this tutorial, you will learn how to solve the error and it’s much easier than you think.
The PHP engine throws the “cannot use object of type stdClass as array” error message due to your code trying to access a variable that is an object type as an array. It is most likely that you’ve tried to access the data with the generic bracket array accessor and not an object operator. Always ensure that you know the variable type before you try to access the data.
See the following example which will throw this error.
Example code 1 (Throws error)
This example shows an object being accessed with an array style syntax which, throws an error of “cannot use object of type stdClass as array”
PHP
$object = new stdClass();
$object->myFirstProperty = 'My First Value';
$object->mySecondProperty = 'My Second Value';
$object->myThirdProperty = 'My Third Value';
$object->myFourthProperty = 'My Fourth Value';
echo
$object["myFirstProperty"];
// Error thrown here
And the second example that won’t throw an error.
Example code 2 (Doesn’t throw an error)
Using the same code whilst using the object operator to access the values will not throw the error.
PHP
$object = new stdClass();
$object->myFirstProperty = 'My First Value';
$object->mySecondProperty = 'My Second Value';
$object->myThirdProperty = 'My Third Value';
$object->myFourthProperty = 'My Fourth Value';
//echo
$object["myFirstProperty"];
echo
$object->myFirstProperty;
Output
My First Value
So how do we get around the error
There are two choices to solve the issue of this error.
Access the values with an object operator as demonstrated in Code Example 2.
Convert the object to an array before accessing it with array style syntax (Example below)
Example code 3 (Doesn’t throw an error)
$object = new stdClass();
$object->myFirstProperty = 'My First Value';
$object->mySecondProperty = 'My Second Value';
$object->myThirdProperty = 'My Third Value';
$object->myFourthProperty = 'My Fourth Value';
$array = json_decode(json_encode($object), true);
echo
$array["myFirstProperty"];
Output
My First Value
Summary
And that is all there is to it, it is simple, yes, but you can be caught out when using the various frameworks such as Laravel. Laravel returns database data via the eloquent library it uses as an object by default and so it must be converted to an array to prevent the error from being thrown.
Source : Paper.li
Comments