2

How do i detect of a certain class has constructor method in it? eg:

function __construct()
{
}
4
  • I think __construct is PHP5 syntax, not? Maybe the tags should be corrected then (removal of php4) Commented Dec 9, 2009 at 7:08
  • 1
    Why do you need to know? it does not affect the ability to make a new instance. You could always consult the PHPDocs. Commented Dec 9, 2009 at 7:10
  • but if the method is in fact private it does affect this ability, but then i don't know how to check it. Commented Dec 9, 2009 at 7:13
  • Or the example be changed to reflect php4 behaviour Commented Dec 9, 2009 at 7:46

4 Answers 4

7

With method_exists I suppose ?

Sign up to request clarification or add additional context in comments.

Comments

5
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).

Comments

4

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.

Comments

1

Reflection API expose isInstantiable()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.