我需要在所有文件都被包含(include)之后确定哪些类继承(extend)了一个父类,所以:
class foo{
}
class boo extends foo{
}
class bar extends foo{
}
我希望能够获取类似这样的数组:
array('boo','bar');
我需要在所有文件都被包含(include)之后确定哪些类继承(extend)了一个父类,所以:
class foo{
}
class boo extends foo{
}
class bar extends foo{
}
我希望能够获取类似这样的数组:
array('boo','bar');
参考Wrikken的回答,结合Scott BonAmi的建议进行修正,得到如下结果:
$children = array();
foreach( get_declared_classes() as $class ){
if( is_subclass_of( $class, 'foo' ) )
$children[] = $class;
}
is_a()
和instanceof
的其他建议都不适用于此,因为它们都期望一个对象实例,而不是一个类名。
如果你需要这样做,那么它看起来像糟糕的代码,基类不应该知道这个。
不过,如果你已经包含了定义(即你不需要包含可能有的新类文件),你可以运行:
$children = array();
foreach(get_declared_classes() as $class){
if($class instanceof foo) $children[] = $class;
}
is_a
而不是instanceof
之外,这基本上就是我的代码...我知道你为什么会这样想,但基类实际上不需要知道任何事情,这更像是一个插件管理器函数 :) - Treyis_a()
和instanceof
对我来说不起作用,因为这两个都期望一个对象,而不是一个类名。 - MikeSchinkelFooable
的接口。interface Fooable{
public function doSomething();
}
2- 所有的目标类必须实现该接口:
class Fooer implements Fooable{
public function doSomething(){
return "doing something";
}
}
class SpecialFooer implements Fooable{
public function doSomething(){
return "doing something special";
}
}
3- 创建一个注册类,将其称为FooRegisterar
class FooRegisterar{
public static $listOfFooers =array();
public static function register($name, Fooable $fooer){
self::$listOfFooers[$name]=$fooer;
}
public static function getRegisterdFooers(){
return self::$listOfFooers;
}
}
4- 在您的启动脚本或被包含在启动脚本中的某个脚本中:
FooRegisterar::register("Fooer",new Fooer());
FooRegisterar::register("Special Fooer",new SpecialFooer());
5- 在你的主代码中:
class FooClient{
public function fooSomething(){
$fooers = FooRegisterar::getRegisterdFooers();
foreach($fooers as $fooer){
$fooer->doSomthing();
}
}
}