PHP/Language Basics/Variable Scope

Материал из Web эксперт
Перейти к: навигация, поиск

Defining Variable Scope

 
<?php
$a = 7;
function test() {
  $a = 20;
}
test();
echo "\$a = $a\n";
?>



local variables

 
<?php
$x  = 4;
function assignx () { 
   $x = 0;
   print "\ $x inside function is $x. <br>";
} 
assignx();
print "\ $x outside of function is $x. <br>";

?>



More Working with Variable Scope

 
<?php
    function getglobal() {
        global $my_global;
        echo "The value of \$foobar is "$foobar"<BR>";
    }
    $my_global = 20;
    getglobal();
?>



Scope of a Variable

<?php
  $a = "asdf";
  function music (){
      $a = "Music is great";
  }
  print $a;
?>



Use variable defined outside function

<?php
  $ilike = "Rock";
  function music(){
      echo "I love listening to $ilike music!", "\n";
  }
  music();
?>



Variable Scope

 
<?php 
  $num;
  function make_triple($arg)
  {
    global $num;
    $num = $arg + $arg +$arg;
    thrice();
  }
  function thrice()
  {
    global $num;
    echo("The value is $num");
  } 
?>
<html>
 <head>
  <title>Variable Scope</title>
 </head>
 <body>
  <h3> <?php make_triple(4); ?> </h3>
 </body>
</html>



Variable Scope: A Variable Declared Within a Function Is Unavailable Outside the Function

 
<html>
<head>
<title>Local Variable Unavailable Outside a Function</title>
</head>
<body>
<div>
<?php
    function test() {
       $testvariable = "this is a test variable";
    }
    print "test variable: $testvariable<br/>";
?>
</div>
</body>
</html>



Variable scope: function

<?php
  increment ();
  increment ();
  increment ();
  function increment () {
      $a=0;
      echo $a;
      $a++;
  }
?>



Variable Scope in Functions

 
function foo( ) {
            $bar = "wombat";
    }
    $bar = "baz";
    foo( );
    print $bar;



Variables Defined Outside Functions Are Inaccessible from Within a Function by Default

<html>
<head>
<title>Variables Defined Outside Functions Are Inaccessible from Within a Function by Default</title>
</head>
<body>
<?php
$life = 42;
function meaningOfLife(){
     print "The meaning of life is $life<br>";
}
meaningOfLife();
?>
</body>
</html>