PHP - Function Variable Scope

Introduction

You can create and use variables within a function.

For example, the following function creates two string variables, $hello and $world, then concatenates their values and returns the result:

Demo

<?php

function helloWithVariables() {
          $hello ="Hello,";
          $world ="world!";
          return $hello. $world;//  w  w  w .  j  a v  a2  s . c o  m
}

echo helloWithVariables(); // Displays"Hello, world!"
?>

Result

Any variables created within a function are not accessible outside the function.

Here, the variables $hello and $world that are defined inside the function are not available to the calling code.

Demo

<?php

        function helloWithVariables() {
          $hello ="Hello,";
          $world ="world!";
          return $hello. $world;/*from  w  ww  .  j  a v  a2s  . com*/
         }

        echo helloWithVariables()."\n";
        echo"The value of \$hello is:'$hello'\n";
        echo"The value of \$world is:'$world'\n";

?>

Result

The names of variables used inside a function don't clash with the names of variables used outside the function.

Demo

<?php
     function describeMyDog() {
       $color ="brown";
       echo"My dog is $color \n";
     }//from w ww .  j a  va  2s.com

     $color ="black";

     describeMyDog();
     echo"My cat is $color \n";
?>

Result