【发布时间】:2011-01-13 18:56:21
【问题描述】:
无论如何,一个包含文件是否可以在其被调用的父范围中使用?下面的例子经过了简化,但作用相同。
本质上,一个文件将被一个函数包含,但希望被包含文件的范围是调用包含它的函数的范围。
main.php:
<?php
if(!function_exists('myPlugin'))
{
function myPlugin($file)
{
if(file_exists($file)
{
require $file;
return true;
}
return false;
}
}
$myVar = 'something bar foo';
$success = myPlugin('included.php');
if($success)
{
echo $myResult;
}
包含的.php:
<?php
$myResult = strlen($myVar);
提前致谢,
亚历山大。
编辑:解决方案
嗯,有点,感谢 Chacha102 的贡献。
现在也可以从类中调用!
main.php
<?php
class front_controller extends controller
{
public function index_page()
{
$myVar = 'hello!';
// This is the bit that makes it work.
// I know, wrapping it in an extract() is ugly,
// and the amount of parameters that you can't change...
extract(load_file('included.php', get_defined_vars(), $this));
var_dump($myResult);
}
public function get_something()
{
return 'foo bar';
}
}
function load_file($_file, $vars = array(), &$c = null)
{
if(!file_exists($_file))
{
return false;
}
if(is_array($vars))
{
unset($vars['c'], $vars['_file']);
extract($vars);
}
require $_file;
return get_defined_vars();
}
包含的.php:
<?php
$myResult = array(
$myVar,
$c->get_something()
);
如果你想引用一个方法,它必须是公开的,但结果符合预期:
array(2) {
[0]=>
string(6) "hello!"
[1]=>
string(7) "foo bar"
}
现在,这并没有任何实际用途,我想知道如何做到这一点的唯一原因是因为我很固执。这个想法进入了我的脑海,并且不会让它打败我:D
<rant>
感谢所有做出贡献的人。除了那个嘘我的人。这是一个足够简单的问题,现在已经发现(复杂的)解决方案存在。
搞砸它是否“符合PHP的做事方式”。曾经告诉客户“哦不,我们不应该那样做,这不是正确的做事方式!”?没想到。</rant>
再次感谢 Chacha102 :)
【问题讨论】:
标签: php function include scope