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;//  ww w .j av  a2  s.  c om
}

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;// www  .j a v  a 2 s.c o  m
         }

        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";
     }/* w  w w .ja v a 2  s.  c  o  m*/

     $color ="black";

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

Result