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!

Recommended Answers

All 3 Replies

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.

Ok I will try that, thank you.

Member Avatar for diafol
<?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;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.