Page 1 of 1

mysql_fetch_object cast as object?

Posted: Tue Feb 28, 2006 9:09 am
by dj1s
So as it seems like their should be an effective way of doing this, my question is as follows.

Inside my class constructor I have AssignVariables() let's say that assigns all the member variables of a given object after the key has been assigned.

My SQL statement will return a single row and assign all of these variables. Using mysql_fetch_object this will look like this:

$this->var1 = $row->var1;
$this->var2 = $row->var2;
$this->var3 = $row->var3;
etc...etc...

It just seems tedious and somewhat unecessary as we're basically just casting the returned object as a custom object, with the same number of variables in a specific order.

So, is this just an accepted problem or is there a commonly used solution to reduce the amount of code reuse?

Posted: Tue Feb 28, 2006 9:28 am
by feyd
I believe you may be able to use a foreach to automate the assignment process.

Re: mysql_fetch_object cast as object?

Posted: Tue Feb 28, 2006 11:03 am
by Christopher
How about:

Code: Select all

$this->row = $row;

// access vars with
$this->row->var1;
$this->row->var2;
$this->row->var3;

Re: mysql_fetch_object cast as object?

Posted: Tue Feb 28, 2006 11:28 am
by dj1s
arborint wrote:

Code: Select all

$this->row = $row;

// access vars with
$this->row->var1;
$this->row->var2;
$this->row->var3;
Perhaps I'm missing something here, are you suggesting having a member variable as an object of the class itself? Wouldn't that instantiate two different objects when the constructor was called?

Posted: Tue Feb 28, 2006 11:39 am
by John Cartwright
I usually keep my rowset in the array, ie.

Code: Select all

$this->data = $row;
and obviously access columms through

Code: Select all

echo $this->data['username'];

hmm...

Posted: Tue Feb 28, 2006 12:00 pm
by dj1s
Probably shouldn't have used $row as I'm returning an object... more like $obj->var1 returned from mysql_fetch_object.

I'm trying to keep this object oriented so I prefer the strongly typed $object->variable rather then referencing a row in an array. Nice to have intellisense in Zend..

It just seems like to me if we have 2 objects, let's say $User and the generic mysql object $Obj, both with the same number of variables in the same order, that a generic cast function would exist that could be used on all classes that would copy the variables out of the generic object into a custom object (assuming they contain the same number of variables).

Posted: Tue Feb 28, 2006 12:14 pm
by neophyte
Fine then:

Code: Select all

$this->data = (object) $row;
echo $this->data->colNam;