Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning objects in php

Tags:

object

php

I see similar questions asked but I seem to have problem with more basic stuff than were asked. How to declare a variable in php? My specific problem is I have a function that reads a DB table and returns the record (only one) as an object.

class User{
   public $uid;
   public $name;
   public $status;
}

function GetUserInfo($uid)
{
   // Query DB

   $userObj = new User();

   // convert the result into the User object.

   var_dump($userObj);   
   return $userObj;
}

// In another file I call the above function.

....

$newuser = GetUserInfo($uid);

var_dump($newuser);

What is the problem here, I cannot understand. Essentially the var_dump() in the function GetUserInfo() works fine. The var_dump() outside after the call to GetUserInfo() does not work.

like image 815
user220201 Avatar asked May 04 '10 13:05

user220201


1 Answers

Using PHP5 it works:

<pre>
<?php

class User{
   public $uid;
   public $name;
   public $status;
}

function GetUserInfo($uid)
{

   $userObj = new User();
   $userObj->uid=$uid;
   $userObj->name='zaf';
   $userObj->status='guru';
   return $userObj;
}

$newuser = GetUserInfo(1);
var_dump($newuser);

?>
</pre>

object(User)#1 (3) {
  ["uid"]=>
  int(1)
  ["name"]=>
  string(3) "zaf"
  ["status"]=>
  string(4) "guru"
}
like image 87
zaf Avatar answered Oct 17 '22 02:10

zaf