Sign in to follow this  
spraff

[web] Nonsensical PHP

Recommended Posts

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 this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
Quote:
Original post by Oluseyi
That 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
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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this