0

I have 2 variables that should be global within its own file. I am attempting to access their set information from a function within that file but I receive nothing but an error. When I hardcode in the information into the function instead of retrieving from the variables, it works perfectly.

<?php
$myVar1 = "Suzy";
$myVar2 = "Billy";

function getNames()
{
    $user1 = $myVar1;
    $user2 = $myvar2;

    return $user1 + $user2;
}
?>

This is similar to what I'm doing. $user1 and $user2 will have nothing in them when it reaches the return statement.

Could anyone help? I am able to access the variables when I include this file into another page, but just can't access them (maybe they aren't instantiated yet?) when I try to from this function.


Thanks!

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by diafol
0

The scope of ordinary variables outside a function remain outside that function. Conversely, the scope of ordinary variables inside a function remain inside that function.

In other words, you cannot declare a variable outside a function and use it inside a function, without using the global keyword.

So what you probably want to do is this:

<?php
$myVar1 = "Suzy";
$myVar2 = "Billy";

function getNames()
{
    global $myVar1;
    global $myVar2;

    $user1 = $myVar1;
    $user2 = $myvar2;

    return $user1 + $user2;
}
?>

The two extra lines I added tell the function that those variables are to be sourced from outside the function.

0
<?php
$myVar1 = "Suzy";
$myVar2 = "Billy";
 
function getNames($var1,$var2)
{
    $user1 = $var1;
    $user2 = $var2;
    return $user1 + $user2;
}

$thename = getNames($myVar1, $myVar2);
?>

You could also pass the variables as parameters. Could I ask why you're adding names (in an arithmetical fashion)? The concatenator (.) would be more appropriate to use with strings:

return $user1 . $user2;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.