View Full Version : Return an array from a function
08-29-2011, 10:40 PM
I have this code
$Sql = "SELECT * FROM members WHERE user_id = '$ID'";
$Res = mysql_query($Sql);
while ($row = mysql_fetch_array($Res))
foreach ($row as $ide => $val)
$userDetails[$ide] = $val;
on a functions.php page which is an include on my inc.header page (so every page has the functions). If i call that function at the start of a page and try echo $userDetails['username']; it doesnt return anything but if in the function i put that it outputs the username.
What am i doing wrong? Or is this undoable.
08-29-2011, 11:15 PM
How are you calling and storing the results of the function?
08-29-2011, 11:17 PM
I called it by doing getUserDetails($_SESSION['userID']);
Howeer i put it into a class and i got it working that way, all i need to do to get info is $user->userDetails['whatever i want'];
I didnt think of using a class when i made the function :P
08-29-2011, 11:23 PM
The only difference between a class and a function is the addition of a context.
When you call a method, same as a function, you need to assign the results to something. In the case of a class, you have assigned it to a member which can be accessed as a part of the object. In a function, you need to actually assign the results: $userDetails = getUserDetails($_SESSION['userID']);. $userDetails in the scope of the call is not the same as the $userDetails in the scope of the function. They are completely different memory sets, so there is no relation to them whatsoever.
08-29-2011, 11:32 PM
Okay so do you mean i should have called the function like
$user = getUserDetails($_SESSION['userID']);
Then got the values by doing this?
$user = $userDetails['username'];
08-29-2011, 11:42 PM
No, $user would contain the results of getUserDetails. You would access it under $user['username'].
Alternatively, methods can be written to accept a reference to write directly into:
function loaduser($iUserID, &$aInto)
$sQry = 'SELECT * FROM user WHERE userid = ' . $iUserID;
if ($q = mysql_query($sQry))
$aInto = mysql_fetch_assoc($q);
$user = array();
08-29-2011, 11:46 PM
Ahh i see :), thank you. Just curious whats the & do infront of $aInto? Ive never seen that before.
08-30-2011, 01:20 AM
It creates a reference to the calling variable. By default, methods and functions with the exceptions of objects will perform operations on a copy of the variable, not the original. Using a reference forces all changes to occur on the original.
Functions can also return by reference so any time a variable is assigned to a function result and later the same function is called again but produces different results would be reflected in the previous variable assignment as well. There are very very few uses for return by reference techniques.
08-30-2011, 06:17 AM
Ahh okay, thanks :).
Powered by vBulletin® Version 4.2.2 Copyright © 2017 vBulletin Solutions, Inc. All rights reserved.