bsmedia Posted April 16, 2012 Share Posted April 16, 2012 I dont know why I'm having so many problems with this. I need to get a variable that defined in an included file inside of a function I've got this Inside file.php I've got the $variable1 and $variable2 defined (they're dynamic/different to each user) include('file.php'); function foo() { GLOBAL $variable1, $variable2; echo $variable1; echo $variable2; } foo(); Yet it outputs nothing? If I Include file.php right inside of the function it works however. Any idea? Quote Link to comment https://forums.phpfreaks.com/topic/261049-get-variable-inside-of-function/ Share on other sites More sharing options...
xyph Posted April 16, 2012 Share Posted April 16, 2012 <?php $var1 = 'foo'; $var2 = 'bar'; function foo( $str1, $str2 ) { echo $str1; echo $str2; } foo( $var1, $var2 ); ?> Use arguments/returns rather than the global keyword. Quote Link to comment https://forums.phpfreaks.com/topic/261049-get-variable-inside-of-function/#findComment-1337875 Share on other sites More sharing options...
RickXu Posted April 17, 2012 Share Posted April 17, 2012 If the page you call foo() has included the file, the global would still work although it's not neat. Like xyph suggested, you should stick to functions and returns or even consider putting them into classes if necessary. Quote Link to comment https://forums.phpfreaks.com/topic/261049-get-variable-inside-of-function/#findComment-1337966 Share on other sites More sharing options...
KevinM1 Posted April 17, 2012 Share Posted April 17, 2012 Use arguments/returns rather than the global keyword. Exactly right. The word 'global' is evil. Forget you ever saw it. Quote Link to comment https://forums.phpfreaks.com/topic/261049-get-variable-inside-of-function/#findComment-1337981 Share on other sites More sharing options...
KevinM1 Posted April 17, 2012 Share Posted April 17, 2012 If the page you call foo() has included the file, the global would still work although it's not neat. Like xyph suggested, you should stick to functions and returns or even consider putting them into classes if necessary. Classes are NOT a stand-in for functions. Classes have a specific use. Quote Link to comment https://forums.phpfreaks.com/topic/261049-get-variable-inside-of-function/#findComment-1337982 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.