Jump to content
  • Advertisement
Sign in to follow this  
spraff

[web] Nonsensical PHP

This topic is 3930 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Quote:
Original post by ToohrVyk
Arguably, 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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!