PHP Check if Variable is an Instance of “Any” Classes

<?php function is_instance($x) { // not an object, not an instance if (!is_object($x)) return false; // <http://php.net/manual/en/language.oop5.magic.php> $m = [ 'construct', 'destruct', 'call', 'callStatic', 'get', 'set', 'isset', 'unset', 'sleep', 'wakeup', 'toString', 'invoke', 'set_state', 'clone', 'debugInfo' ]; foreach ($m as $v) { if (method_exists($x, '__' . $v)) return $x; } return false; } // check if `$foo` is an instance of `Foo` class $foo = new Foo; if ($foo instanceof Foo) { echo 'true'; } // check if `$foo` is an instance of any class $foo = new Bar; if (is_instance($foo)) { echo 'true'; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.