Nadler Banit
Nadler Banit

Reputation: 21

PHP using inner function variable in another function

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

Answers (4)

RadhaKrishna
RadhaKrishna

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

Ja͢ck
Ja͢ck

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

Yogesh Suthar
Yogesh Suthar

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."";
}

Output

using echo in function Codepad

RajithaRajithaYour username is  tobaco

Output1

using return in function Codepad

RajithaYour username is Rajitha tobaco

Upvotes: 2

John V.
John V.

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

Related Questions