Home > Article > Backend Development > How to determine whether the string in a variable is an instantiable class in PHP?
<code>$a='myclass'; class myclass{ static function aa(){ print_r(9966); } } </code>
How to determine whether $a
is an instantiable class?
<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