Mzor Posted March 20, 2009 Share Posted March 20, 2009 This is frustrating me... I'll let this piece of code do the explaning ofr me: <?php $test = array ('one', 'two'); $test['one'] = 1; $test['two'] = 2; function oneAndTwo(){ echo $test['one'] . '<br />'; echo $test['two']; } oneAndTwo(); ?> This returns the error: Notice: Undefined variable: test in C:\wamp\www\test.php on line 11 Notice: Undefined variable: test in C:\wamp\www\test.php on line 12 Now, when I echo the variable $test['one'] outside of the function, it works just fine. hy is it not working when I echo it using a function? Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted March 20, 2009 Share Posted March 20, 2009 This is to do with variable scope. Functions have their own variable scope. To be able to use a variable set outside of a function you can, either define the variable within the function as global, eg: $myvar = 'hello'; function foo() { global $myvar; echo $myvar; } Or pass the variable to the function $myvar = 'hello'; function foo($var) { echo $var; } The same applies to variables set within a function. In order to retrieve variables that were defined within a function you can either define it as global (as shown above) or return the the value the variable, eg: function add_up($n, $y) { $result = $n + $y; return $result; } $result = add_up(5, 6); // OR echo add_up(5, 6); ?> Quote Link to comment Share on other sites More sharing options...
Mzor Posted March 20, 2009 Author Share Posted March 20, 2009 Ah, ok. Thanks. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.