Error: cannot use object of type stdClass as array error in PHP or Wordpress

Share:
Error: cannot use object of type stdClass as array error in PHP or Wordpress


Many of you facing error "cannot use object of type stdClass as array". In this post you will learn how can we resolve this error? This post will show you when you get this error message and How can you resolve this error eassily.

PHP or Wordpress show "cannot use object of type stdClass as array" error message when your code tring to access the Object type  varible as an Array. It is possible that you’ve tried to access your object type variable with the generic bracket Array accessor not an object operator. 

See the below example which is able to throw this error.


Example 1: Below example is show error

You can see in blow example  we are trying to access the object type varibale using the array. throws an error of “cannot use object of type stdClass as array

 $object = new stdClass();  

 $object->firstVariable = 'My First Value';  

 $object->secondVariable = 'My Second Value';  

 $object->thirdVariable = 'My Third Value';  

 $object->fourthVariable = 'My Fourth Value';  

 echo $object["firstVariable"]; // Error thrown here  


Now you can see the second example without error

Example 2: Below example not throw error

You can see the same example, but in this example you can see the object variable are using the object operator to show the value. You can see this example is not throw an error

 $object = new stdClass();  

 $object->firstVariable = 'My First Value';  

 $object->secondVariable = 'My Second Value';  

 $object->thirdVariable = 'My Third Value';  

 $object->fourthVariable = 'My Fourth Value';  

 echo $object->firstVariable;  

 OutPut  

 My First Value  


Solutions

We have two different solutions to resolve this issue. 

  1. Convert the object  type varible to an array variable before accessing it with array 
  2. Access the object type variable values with an object operator as show in Example 2

 $object = new stdClass();  
 $object->firstVariable = 'My First Value';  
 $object->secondVariable = 'My Second Value';  
 $object->thirdVariable = 'My Third Value';  
 $object->fourthVariable = 'My Fourth Value';  
 $array = json_decode(json_encode($object), true);  
 echo $array['firstVariable'];  
 OutPut  
 My First Value  



No comments

Ads