nloding Posted May 14, 2008 Share Posted May 14, 2008 The topic title doesn't quite illustrate what I mean. Here's my setup: <?php //File: includes/page.inc function getPage($page = null) { if($page == null) $page = "home"; include_once("$page.php"); } //End page.inc //File: index.php include_once('includes/page.inc'); $db = new DBClass(); getPage(); //End index.php //File: test.php include_once('includes/page.inc'); $db = new DBClass(); include_once('home.php'); //End test.php With index.php, the home.php page that is included using the function does NOT have access the $db variable declared right above it. But if I skip the function call, and just include home.php, home.php DOES have access to $db. If both are calling include_once, why the difference in scope? Link to comment https://forums.phpfreaks.com/topic/105603-help-understanding-include_once-function/ Share on other sites More sharing options...
DarkWater Posted May 14, 2008 Share Posted May 14, 2008 I always find problems with including pages inside of functions, not sure why though. I've never really looked into it. You'd be better off just coding it outside of a function. Link to comment https://forums.phpfreaks.com/topic/105603-help-understanding-include_once-function/#findComment-541004 Share on other sites More sharing options...
nloding Posted May 14, 2008 Author Share Posted May 14, 2008 I'm using a Page class now that sets my page, so I'm doing this: include_once($page->getPage()); It works fine, just not what I wanted my code to look like. And I'm curious as to why the include works differently. Link to comment https://forums.phpfreaks.com/topic/105603-help-understanding-include_once-function/#findComment-541012 Share on other sites More sharing options...
PFMaBiSmAd Posted May 14, 2008 Share Posted May 14, 2008 Two words - variable scope. This has nothing to do with include(). Variables are not available inside of functions unless you pass them into the function as parameters. Link to comment https://forums.phpfreaks.com/topic/105603-help-understanding-include_once-function/#findComment-541022 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.