开发者

PHP: How to detect if a certain class has constructor?

开发者 https://www.devze.com 2022-12-13 18:40 出处:网络
How do i detect of a certain class has constructor method i开发者_如何学Cn it? eg: function __construct()

How do i detect of a certain class has constructor method i开发者_如何学Cn it? eg:

function __construct()
{
}


With method_exists I suppose ?


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;
}

Using method_exists() can have it's pros, but consider this code

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;

This will output "g has constructor" and also result in a fatal error when creating a new instance of g. So the sole existance of a constructor does not necessarily mean that you will be able to create a new instance of it. The create function could of course return the same instance every time (thus making it a singleton).


There's a couple ways, and it sort of depends on exactly what you're looking for.

method_exists() will tell you if a method has been declared for that class. However, that doesn't necessarily mean that the method is callable... it could be protected/private. Singletons often use private constructors.

If that's a problem, you can use get_class_methods(), and check the result for either "__construct" (PHP 5 style) or the name of the class (PHP 4 style), as get_class_methods only returns methods that can be called from the current context.


Reflection API expose isInstantiable()

  $reflectionClass = new ReflectionClass($class);
  echo "Is $class instantiable?  ";
  var_dump($reflectionClass->IsInstantiable()); 
0

精彩评论

暂无评论...
验证码 换一张
取 消