Re: Include and require
| From: | Adam Zey | Date: | Mon, 14 Aug 2006 22:01:23 +0000 |
| Subject: | Re: Include and require | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-240659@lists.php.net to get a copy of this message | ||
Dave Goodchild wrote:
I use a config file too. That was a sanity check. The file extract looked like this: $months = array(1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April', 5 => 'May', 6=> 'June',$foo = "bar"; if ( $foo == "bar" ) { $baz = "narf"; } echo $baz; That code will output nothing, because $baz is empty by the time I try to output it. The solution that I use is this: $foo = "bar"; $baz = ""; if ( $foo == "bar" ) { $baz = "narf"; } echo $baz; In which case the output would be "narf", because the variable existed before I changed it in the if. This sounds like it might be your problem, though I can't know without seeing the code. Regards, Adam Zey.7 => 'July', 8 => 'August', 9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December');which was called in with require_once. The reference to $months in the calling page, checked with var_dump, was NULL. When I wrapped it like this: function getmonths() {$months = array(1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April', 5 => 'May', 6=> 'June', 7 => 'July', 8 => 'August', 9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December'); return $months;} it worked. Not sure why the simple variable didn't work. On 14/08/06, *Adam Zey* <azey@nit.ca <mailto:azey@nit.ca>> wrote:Dave Goodchild wrote:Hi all - I have several require_once statements in my web app toload insmall function libraries. A common one bundles a variety offunctions tohandle date math and map month numbers to month names. Ioriginally definedan array in that file plus a bunch of functions but when Iloaded the page,the array variable, referenced further down the page, was NULL.I wrapped afunction def around the array and returned it and all was fine. I may be suffering from mild hallucinations, but can you not define variables in a required file? It is not a scope issue as thearray variableis referenced in the web page, not in any function.I know for a fact that you can define variables in PHP 4 and 5. The idea behind include and require is little more complex than copying and pasting the code. Many of my scripts include a config.php which has various variables created with setting information.Regards, Adam Zey.-- http://www.web-buddha.co.uk http://www.projectkarma.co.uk Was the $months variable created inside an if statement or something else? PHP's rules of scope say that variables created inside a code block (like an if, a for, a while, a foreach), they stop existing the moment you exit that code block. So this: