Basic PHP problems
When I use this function variables created by the included scripts are retained within the scope of this function.
function reqscript($script)
{
$include_dir = 'inc/';
$page_ext = '.php';
include($include_dir.$script.$page_ext);
}
Is开发者_运维知识库 there any way of me not having to use the following method?
include(buildfilename('...'));
If you want to define some variables in your included file, you have to use $GLOBALS
.
e.g: $foobar = 42;
should be $GLOBALS['foobar'] = 42;
So $foobar
is available in the global scope (outside of functions).
But I would prefer a buildfilename()
method.
Your answer is on php.net already, use return at the end of your included file.
http://php.net/manual/en/function.include.php
Example #5:
return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1
?>
I suggest you adopt your code to use the buildfilename()
method, like Floem suggested. However, if you can't or do not wish to do so, here's a simple wrapper to import variables to the global namespace:
class Req {
public function __construct($src) {
include($src);
foreach (get_object_vars($this) as $name => $value) {
$_GLOBALS[$name] = $value;
}
}
}
function reqscript($script) {
$include_dir = 'inc/';
$page_ext = '.php';
new Req($include_dir . $script . $page_ext);
}
精彩评论