What you have encountered here is the concept of variable scope in PHP.
What ever is defined outside of a function is irrelevant inside a function, due to it having its own scope.
So you can do what you intend in multiple ways.
Method 1: Using Global
Keyword
$a = 1; $b = 2;
function Sum(){
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
Note: The global
keyword makes the variable available to the "global
" scope, and it can be defined and accessed anywhere from any class or even from outside during the runtime, due to which, from maintenance and debugging perspective it creates a lots of hassle hence it is very much frowned upon and considered a last resort tool.
Method 2: Function Argument
$name = "john";
$lastname = "smith";
function fullname($name, $lastname){
$name .= $lastname;
return $name;
}
echo fullname($name, $lastname);
Method 3: Using Reference
function foo(&$var){
$var++;
}
$a=5;
foo($a);
// $a is 6 here