Reputation: 24061
I set a var:
$name = "john";
Then I have a function:
function whatever(){
$name .= " smith";
}
Outside the function I want to dump the name:
var_dump($name);
But just john is output. I've tried using:
function whatever() use ($name) {
var_dump($name) //john
$name .= " smith";
}
But the final var dump outside the function still does not append smith. Where am I going wrong?
Upvotes: 0
Views: 90
Reputation: 13928
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
Upvotes: 0
Reputation: 1016
simpliest way to do that:
$name = "john";
function merge($name) {
return "$name smith";
}
$name = merge($name);
echo $name; // shows you: john smith
i think this is exactly what you was looking for
don't try to use outer scope vars like in javascript. thats not testable and bad practice
Upvotes: 1
Reputation: 490
Its a case of variable scope. What you can do here is getting it via global or passing a parameter:
// Pass by parameter
$name = "john";
function whatever($name){
$name .= " smith";
return $name;
}
var_dump(whatever($name));
// Calling it via global
function whatever2(){
global $name;
$name .= " smith";
return $name;
}
var_dump(whatever2());
If you still want to use "use":
$name2 = "john";
$full_name = function () use ($name2){
return $name2 . " smith";
};
var_dump($full_name());
Upvotes: 0