tags:

views:

591

answers:

3

Global scope allows you to use a variable in a function that was defined outside the function. eg

$a=1;
function $test(){
echo $a;
}

//outputs 1

but why is it that if I define a variable with an array I cannot use it the same way?

$test = array(
0=>'zero', 
1=>'one', 
2=>'two',
3=>'three', 
);

function doesntWork($something){
echo "My favorite number is " . $test[$something]; 
}

//outputs My favorite number is 0

How do i pass the array into the function without having to recopy the array into the function itself.

any explanation would be appreciated thanks

+3  A: 

Your first example should not output 1. The only way to make variables global in a particular function is to use the global keyword like this:

function test() {
    global $a;
    echo $a;
}

function doesWork($something) {
    global $test;
    echo "My favorite number is " . $test[$something]; 
}

More info here: http://ca2.php.net/manual/en/language.variables.scope.php

yjerem
i heard using globals all the time is bad practise... should I wrapping them in a class?
chris
A: 

PHP doesn't have implicit global scoping; you must use the the global keyword to access "global" variables.

$a outputting 1 is probably due to an intricacy of PHP's dubious handling of variables.

orlandu63
+2  A: 

script #1 is not correct. neither does it work (function $test() {...}), nor does it output "1". and globals ARE bad practice. wrapping them in a class got nothing to do with it. classes are not a solution for random problems not related to object orientation.

just pass $a as a parameter:

<?php 
  $a=1; 
  function test($foo) { 
    echo 'number ' . $foo; 
  }; 

  test($a);
  // -> "number 1". 
 ?>

script #2:

<?php
  $test = array(
    0=>'zero', 
    1=>'one', 
    2=>'two',
    3=>'three', 
  );

  function doesntWork($test, $something){
    echo "My favorite number is " . $test[$something]; 
  }

  doesntWork($test, mt_rand(0,3));
?>
Schnalle
ok so you need to redefine the array inside the function?I asked about classes because ive seen people use public variable with OOP and only define variables once. Im looking for best practisesthanks
chris
thanks thats exactly what i needed. I ended up doing it with OOP class works{ var $a; function favNum{echo $this->a;} }
chris