我如何检测某个类中是否有构造函数方法?例如:
function __construct()
{
}
Run Code Online (Sandbox Code Playgroud)
function hasPublicConstructor($class) {
try {
$m = new ReflectionMethod($class, $class);
if ($m->isPublic()) {
return true;
}
}
catch (ReflectionException $e) {
}
try {
$m = new ReflectionMethod($class,'__construct');
if ($m->isPublic()) {
return true;
}
}
catch (ReflectionException $e) {
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
使用method_exists()可以拥有它的优点,但请考虑此代码
class g {
protected function __construct() {
}
public static function create() {
return new self;
}
}
$g = g::create();
if (method_exists($g,'__construct')) {
echo "g has constructor\n";
}
$g = new g;
Run Code Online (Sandbox Code Playgroud)
这将输出"g has constructor",并且在创建g的新实例时也会导致致命错误.因此,构造函数的唯一存在并不一定意味着您将能够创建它的新实例.create function当然可以每次都返回相同的实例(从而使它成为单例).