Why can't I put this object in an array?

In PHP, you can usually put an object in an array, for example:

class Car{} $car = new Car(); // This runs without error $array['vehicle'] = $car; 

I have a custom MVC environment that I created, and I need a controller to get the ORM object from the model so that it can pass this view. So, I initialize my custom object:

 $user = new User(2); 

Now I want to put this custom object in the $data array so that it can be passed to the view:

($ user-> data returns an ORM object)

 $array['user'] = $user->data; 

The problem is that after that I get the following error:

  Object of class ORM could not be converted to string 

What am I doing wrong? Is there something I'm missing?
Thanks for any help in advance.

Edit: here the data $ user-> is referenced, this is from the class User constructor:

 $this->data = ORM::for_table("users")->find_one($this->user_id); 

(I use Idiorm as ORM)

+6
source share
1 answer

If you get an error, for example:

 Object of class ORM could not be converted to string 

The first question you should ask is โ€œwhy should it be converted to a stringโ€? An array can take a string just fine, so you can assume that $data is actually a string, and PHP thinks you want to change $data[0] .

As you have seen, dynamically typed languages โ€‹โ€‹can leave you stupefied if you are not careful. When your variables display suspicious behavior, try to see what is actually in them using var_dump() .

It is also a good idea to explicitly initialize arrays (for example: $my_array = array(); ) before using them.

+3
source

Source: https://habr.com/ru/post/897855/


All Articles