Reputation: 21
I tried this code today! But it's not giving the output I expected.. this is my code..
<?php
namePrint('Rajitha');
function namePrint($name) {
echo $name;
}
wrap('tobaco');
function wrap($txt) {
global $name;
echo "Your username is ".$name." ".$txt."";
}
?>
This code will print on screen
RajithaYour username is tobaco
but I want to get
RajithaRajithaYour username is tobaco
My question is: why is the $name variable in the wrap function not working?
Thanks.
Upvotes: 0
Views: 104
Reputation: 312
$name should be declared and initialized as global variable.then you can the output you need.
The code should look like this.
<?php
$name = 'Rajitha';
namePrint($name);
function namePrint($name){
echo $name;
}
wrap('tobaco');
function wrap($txt){
global $name;
echo "Your username is ".$name." ".$txt."";
}
?>
Upvotes: -1
Reputation: 173562
If you want to wrap a function around another you could simply pass a closure as one of the arguments:
function wrap($fn, $txt)
{
echo "Your username is ";
$fn();
echo ' ' . $txt;
}
wrap(function() {
namePrint('Rajitha');
}, 'tobaco');
This construct is very delicate; using function return values is more reliable:
function getFormattedName($name) {
return $name;
}
echo getFormattedName('Jack');
Then, the wrap function:
function wrap($fn, $txt)
{
return sprintf("Your username is %s %s", $fn(), $txt);
}
echo wrap(function() {
return getFormattedName('Jack');
}, 'tobaco');
Upvotes: 1
Reputation: 30488
Never use echo
inside function to output the result. And never use global
for variables.
You used echo
inside function and because of that you get unexpected output.
echo namePrint('Rajitha');
function namePrint($name){
return $name;
}
echo wrap('tobaco');
function wrap($txt){
//global $name;
return "Your username is ".namePrint('Rajitha')." ".$txt."";
}
RajithaRajithaYour username is tobaco
RajithaYour username is Rajitha tobaco
Upvotes: 2
Reputation: 4670
Another option would be to pass $name as a parameter to the wrap function.
<?php
$name = 'Rajitha';
function namePrint($name){
echo $name;
}
function wrap($txt, $name){
echo "Your username is " . $name . " ". $txt;
}
namePrint($name);
wrap('tobaco', $name);
?>
Upvotes: 0