Skip to content

Instantly share code, notes, and snippets.

@hopeseekr
Created November 2, 2017 09:50
Show Gist options
  • Save hopeseekr/afd234c470182eb86e3e81b73a66d558 to your computer and use it in GitHub Desktop.
Save hopeseekr/afd234c470182eb86e3e81b73a66d558 to your computer and use it in GitHub Desktop.
Shows the failures of method_exists and the salvation of is_callable.
<?php
class Foo
{
protected function hi()
{
echo "Foo!\n";
}
}
class Bar
{
public function __call($name, $arguments)
{
echo "Bar!\n";
}
}
$foo = new Foo();
$bar = new Bar();
if (method_exists($foo, 'hi')) {
echo "The method $foo->bar() exists. But it is protected! IF I had called it, I would have died!!\n";
}
if (!method_exists($bar, 'hi')) {
echo "Unfortunately, `method_exists` doesn't care that we have a __call() method...We have failed :(\n";
}
if (!is_callable([$foo, 'hi'])) {
echo "Fortunately, `is_callable()` is smart and will not run a protected method $foo->bar().\n";
}
if (is_callable([$bar, 'hi'])) {
echo "The method doesn't exists. But __call() does. So all is well!\n\n";
$bar->hi();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment