Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I place this object into an array?

Tags:

php

In PHP, you can normally place an object in an array, like so:

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

I have a custom MVC framework I've built, and I need the controller to get an ORM object from the model, so it can pass that to the view. So, I initialize my user object:

$user = new User(2);

Now, I want to put that user object into a $data array so it can be passed to the view:

($user->data returns an ORM object)

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

The problem is, after doing this, I receive 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's what $user->data refers to, this is from the constructor of class User:

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

(I'm using Idiorm as an ORM)

like image 484
element119 Avatar asked Sep 22 '11 18:09

element119


1 Answers

If you get an error message like:

Object of class ORM could not be converted to string

The first question you should ask is, "why does it have to be converted to a string"? An array can take a string just fine, so you can guess that $data is actually a string and PHP thinks you want to modify $data[0].

As you've seen, dynamically typed languages can leave befuddled if you aren't careful. When your variables show suspect behavior, try to see what's actually in them using var_dump().

It's also a good idea to explicitly initialize arrays (eg: $my_array = array();) before using them.

like image 196
NullUserException Avatar answered Sep 28 '22 22:09

NullUserException