TeoAlmonte
TeoAlmonte

Reputation: 107

How do I call a variable in another function with PHP?

Hello I am trying to call a variable form a previous function into my next function. I tried using the global but I could not get it to call the variable from the previous function. How can I call the $hisname or $shorter variable in the function called "location"?

<?php
    function name( $hisname) {
    global $shorter;
    $shorter = str_replace(' ', '', strtolower($hisname));
?>

<p>
    <?php print $hisname; ?>
<Br>
    <?php print $shorter; ?>
</p>

<?php
    }
?>

    <?php name('Mike Smith'); ?>

<?php 
    function location($place) {
?>

<p>
    <?php print ($hisname) ?> lives in <?php print $place; ?>
</p>

<?php
    }
 ?>

    <?php location('New York'); ?>

You can see a demo here demo on viper-7

Upvotes: 0

Views: 39

Answers (3)

TeoAlmonte
TeoAlmonte

Reputation: 107

I actually got it working. Ended up using global and calling the variable on both functions. This seemed to get the job done easily. Thanks for the help anyways.

<p> <?php echo $hisname; ?> likes to eat <?php echo $food; ?> <p>
<p> <?php echo $shorter; ?> <p>

<?php
   }
 ?>

<?php name('Mike Smith', 'Apples'); ?>


<?php 
    function location($place) {
    global $shorter;
 ?>

<p>
    <?php echo $shorter; ?> lives in <?php print $place; ?>

</p>

<?php
    }
?>

<?php location('New York'); ?>

Demo Here

Upvotes: 0

Niranjan N Raju
Niranjan N Raju

Reputation: 11987

<?php
global $shorter;
function name($hisname) {

    $shorter = str_replace(' ', '', strtolower($hisname));
    return $shorter;
    ?>



    <?php
}
?>

<?php $hisname = name('Mike Smith');
?>

<p>
        <?php print $hisname; ?>
        <Br>
        <?php print $shorter; ?>
    </p>

<?php

function location($place, $hisname) {
    ?>

    <p>


        <?php print ($hisname) ?> lives in <?php print $place; ?>
    </p>

    <?php
}
?>

<?php location('New York', $hisname); ?>

Upvotes: 1

Aftab Ahmad
Aftab Ahmad

Reputation: 344

Check the following code. hope you will get concept

<?php
function name( $hisname)
{
global $shorter;
$shorter = str_replace(' ', '', strtolower($hisname));
return $hisname;
}
?>

    <?php $name = name('Mike Smith'); echo $name; ?>

<?php 
    function location($place) {
    global $name;
?>

<p>
    <?php echo $name; ?> lives in <?php print $place; ?>
</p>

<?php
    }
 ?>

    <?php location('New York'); ?>

Upvotes: 1

Related Questions