tags:

views:

53

answers:

2

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.

Thanks for any help.

  • S
A: 

First create a new instance of your User class. Then use that instance to call your function and provide the $uid parameter so your query gets executed like it shoudl. If there is a match in your datatable your Userobject will get filled with the DB-results.

Personally I prefer using the static calls, it makes your code much more readable and compact.

Difference:

$userObj = new User();
$user = $userObj->GetUserInfo('your uid');

Or

$user = User::GetUserInfo('your uid');

And I see a strange } at line 4. Correct me if I'm wrong, but I think it should be after the } from the function GetUserInfo($uid).

Ben Fransen
From the code sample above, the GetUserInfo() function isn't a method on the class, it's a separate function.
richsage
I've noticed that too, after i posted my first answer. But then it's a wacky implementation of an OOP solution to get a UserObject, at least, in my opinion.
Ben Fransen
And I'm pretty sure that if he just moves the accolade to the line after the GetUserInfo function (which then becomes a method) it should work fine. P.s. don't forget to add the prefix `public` in front of `function`.
Ben Fransen
Ben, I was simplifying the code for the sake of posting. I do understand its not a good OOP implementation. I did find the problem though, its a lot sillier than I thought like I mentioned above. Thanks for all your help.
You're welcome ;) I was not implifieng that you don't know OOP ;)
Ben Fransen
implifieng? he he.. I like the spelling even better.
@User220201: Yeah I'm sorry for the typo!, @Unknown: It's a real treat getting downvoted without any comment, even though I gave a working solution!
Ben Fransen
+1  A: 

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"
}
zaf