# [web] Nonsensical PHP

## Recommended Posts

spraff    100
Can anyone tell me why this code:
<?php
$x = ''; function foo () { return$x;
}

if (true) {
$x = 'OK'; echo$x.foo();
}
?>


Prints "OK" and not "OKOK"? Thanks

##### Share on other sites
Oluseyi    2103
That code doesn't compile. Assuming we fix your first line (so it's $x = '';), then the$x inside of foo() is not the same as the one outside: by default, a variable used inside of a PHP function is limited to function local scope.

PHP variable scope.

You need to introduce the global keyword inside of foo():
function foo() {  global $x; return$x;}

ToohrVyk    1595
Quote:
 Original post by OluseyiThat code doesn't compile. Assuming we fix your first line (so it's $x = '';) Arguably, this is just the forum turning '' into a single ''. #### Share this post ##### Link to post ##### Share on other sites Oluseyi 2103 Quote:  Original post by ToohrVykArguably, this is just the forum turning '' into a single ''. Good call. I had to use an HTML entity to get around that. My bad, spraff. #### Share this post ##### Link to post ##### Share on other sites Sonnenblume 222 As previously said, the reason its not printing "OKOK" is because of variable scope. Just because the variables both have the same name doesnt mean that they will both have the same value. In this case, the variable$x which is declared within the function foo wont have the same value as any other instance of it declared outside of the function.

I'm not sure if this is helpful for what you are trying to do it, but you could modify your code so that you pass your variable $x into foo as paremter, and then have it returned once the function is called <?php$x = '';
function foo ($parameter) { return$parameter;
}

if (true) {
$x = 'OK'; echo$x.foo(\$x);
}
?>

Edit: or just do what Oluseyi said :)

##### Share on other sites
The-Winner    122
If you increase your Warning level, you will get notices when accessing variables which are NULL. But notice free code will make code which works with valid NULL values more clumsy.