Home  >  Article  >  Backend Development  >  How to determine whether the string in a variable is an instantiable class in PHP?

How to determine whether the string in a variable is an instantiable class in PHP?

WBOY
WBOYOriginal
2016-08-08 09:06:581613browse

<code>$a='myclass';

class myclass{
    static function aa(){
        print_r(9966);
    }
}
</code>

How to determine whether $a is an instantiable class?

Reply content:

<code>$a='myclass';

class myclass{
    static function aa(){
        print_r(9966);
    }
}
</code>

How to determine whether $a is an instantiable class?

It can be done using reflection, you can refer to: ReflectionClass::isInstantiable

For example:

<code class="php">class myclass{
    static function aa(){
        print_r(9966);
    }
}

$a='myclass';

$reflectionClass = new ReflectionClass($a);

if($reflectionClass->isInstantiable()) {
    echo "类 $a 是可以实例化的";
} else {
    echo "类 $a 不可以实例化";
}</code>

The stupidest method:

<code><?php
$a='myclass';

class myclass{
  static function aa(){
      print_r(9966);
  }
}

if (@new $a)
{
  echo 'yes';
}
else
{
  echo 'sorry';
}</code>

========
Ah hahaha, what a fool: class_exists

class_exists($a)


Sorry, class_exists cannot meet the original poster’s needs!
Please see @aisuhua’s answer

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn