【发布时间】:2011-11-04 17:03:07
【问题描述】:
当我们在 PHP 中包含文件时,它们会以某种方式被缓存。因此,如果一个包含一个类定义,当我们尝试包含它两次时,我们会收到一个错误消息“无法重新声明类”。
但是是否有可能在范围设置为当前函数的情况下调用包含文件代码,比如说?
例如如果我们有两个文件:
moo.php:
<?php
class Moo
{
function __construct()
{
echo "hello, world!" . PHP_EOL;
}
}
?>
main.php:
<?php
function foo()
{
include("moo.php");
new Moo();
}
foo();
new Moo(); // <-- here should be an error saying "could not find class Moo"
include("moo.php");
new Moo(); // <-- and here should not
?>
就我所尝试的而言,eval(file_get_contents("moo.php")); 和命名空间都没有以最少的代码产生预期的效果...
【问题讨论】: