Roy
Roy

Reputation: 745

Custom function losing return variable value

I have a custom function which is meant to return certain values on successful completion. In short, the relevant section looks like this:

function register($email, $username, $password)
{
....
$return = array();
$return['code'] = 4;
$return['email'] = $email;
var_dump($return);
echo "<h1>SUCCESS</h1>";
return $return;
}

I can confirm the function does actually reach this stage, because just above the code posted is a SQL query which successfully adds a row to the database and I can also see the 'SUCCESS' message gets posted.

The var_dump inside the function returns the following:

array (size=2)
'code' => int 4
'email' => string '[email protected]' (length=13)

So far, so good. However, if I then go and actually call this function $return is empty. For example, if I do this:

register($email, $username, $password);
var_dump($return);
echo "<h1>Return code & email: $return & ".$return['code']." ".$return['email']."</h1>";

The function runs successfully, a new user is registered and I see 'SUCCESS', but I don't get the $return array returned. var_dump returns this:

string '' (length=0)

And calls to $return['code'] and $return['email'] are met with Warning: Illegal string offset. What am I doing wrong?

Upvotes: 0

Views: 161

Answers (4)

Nagasaki
Nagasaki

Reputation: 58

the mistake is when you call your function:

register($email, username, password);

thinks will be better if you do:

$return = register($email, $username, $password);

Upvotes: 1

Dom
Dom

Reputation: 7325

You must do $return = register($email, $username, $password);

Upvotes: 1

Till Helge
Till Helge

Reputation: 9311

You need to assign the return value to a variable:

$register = register($email, $username, $password);

return $register doesn't mean that the function will create a variable $register in the calling scope, but rather that it will return the content of $register to the calling scope, which then has to figure out what to do with it, e.g. assigning it to a variable.

Upvotes: 2

MatthewMcGovern
MatthewMcGovern

Reputation: 3496

You're calling the function and returning a value, but you're not grabbing the return value.

$return = register($email, $username, $password);

Upvotes: 4

Related Questions