我正在尝试弄清楚如何在运行时导入大量的PHP类函数。例如...
class Entity
{
public function __construct($type)
{
require_once $type."_functions.php"
}
// ...
}
$person = new Entity("human");
$person->sayhi();
$cow = new Entity("cow");
$cow->sayhi();
human_functions.php:
class Entity redefines Entity
{
public function sayhi()
{
echo "Hello world!";
}
}
cow_functions.php:
class Entity redefines Entity
{
public function sayhi()
{
echo "Moo!";
}
}
我发现了几种可能的方法,例如classkit_method_redefine()
和runkit_method_redefine()
(它们是“实验性”的,并且无法修改当前运行的类)。 我现在使用的是PHP 5.3.3,所以我不能使用Traits(不确定那是否是我要找的东西)。 我已经成功地重新定义了处理程序变量,像这样:
// Example 2:
class OtherEntity { /* Code Here */ }
class Entity
{
public function __construct($type)
{
global $foo;
unset($foo);
$foo = new OtherEntity();
}
}
$foo = new Entity();
但是,这感觉像是一种非常hacky的方法。更重要的是,如果我不命名每个类
$foo
的实例,那么它将无法工作。有没有什么解决方法可以达到我想做的事情?注意:我知道我可以扩展一个类,但在我的情况下,当Entity类被初始化时,没有安全的方法预先知道它需要用哪个子类来初始化。也许我可以编写一个方法,例如:
public function changeClass
{
this->class = OtherEntity;
}
感谢您的帮助!