Blog
Here is a typical example of what I’m talking about:
if (method_exists($object, 'SomeMethod'))
{
$object->SomeMethod($this, TRUE);
}
The purpose of this code snippet is quite easy to understand (even if I don’t encourage to do this kind of not-very-OOP-stuff): having an object named “$object”, we try to know if it has a method named “SomeMethod”, if so, we call it, and provide some arguments to it.
Yes, but…
This code will probably run very well during all its lifetime, but what if the object’s method is not visible from the current scope (like… a private or protected method)? PHP’s method_exists() function does what it says: it checks if the provided class or object has a method named like the provided one, and returns TRUE if so, or FALSE if not, visibility is not questionned. So, if you provide a private or protected existing method name (being out of current scope) to method_exists(), you’ll get TRUE as the return value, and a nice “Fatal error: Call to private method…”, immediately terminating the current script execution.
The right tool for the right job
The real intent of the previous code snippet was in fact to know if the application could call a method on the object, from the current scope.
This is why (among other reasons) is_callable() is part of the PHP built-in functions.
How does it work?
is_callable() receives a callback as its first argument, which, in our case, consists of an array of two values: the first being an object (or a string holding a class name), and the second being a string holding a method name. is_callable() returns TRUE when the provided callback can be called from the current scope, or FALSE if not.
if (is_callable(array($object, 'SomeMethod')))
{
$object->SomeMethod($this, TRUE);
}
Here is another snippet of code to illustrate the differences between method_exists() and is_callable() in action:
class Foo {
public function PublicMethod() {}
private function PrivateMethod() {}
public static function PublicStaticMethod() {}
private static function PrivateStaticMethod() {}
}
$foo = new Foo();
$callbacks = array(
array($foo, 'PublicMethod'),
array($foo, 'PrivateMethod'),
array($foo, 'PublicStaticMethod'),
array($foo, 'PrivateStaticMethod'),
array('Foo', 'PublicMethod'),
array('Foo', 'PrivateMethod'),
array('Foo', 'PublicStaticMethod'),
array('Foo', 'PrivateStaticMethod'),
);
foreach ($callbacks as $callback) {
var_dump($callback);
var_dump(method_exists($callback[0], $callback[1])); // 0: object / class name, 1: method name
var_dump(is_callable($callback));
echo str_repeat('-', 40), "\n";
}
Run it, and you’ll see that every test returns TRUE with method_exists(), even private methods, while is_callable() returns FALSE for these (and will also trigger strict errors with non-static methods being queried as static ones, be aware of this).
More details
is_callable() has other uses, like checking the syntax of the provided callback, without checking if there really is a class or a method with the provided names.
Like method_exists(), is_callable() can trigger a class autoloading process if the provided class is not already loaded.
If an object has the magic __call() method implemented, then is_callable() will return TRUE for any non-existent method, while method_exists() will return FALSE. I guess the same behavior can be observed with the recent (PHP 5.3.0) __callStatic() magic method, but I did not test it (yet).
Everything else you need to know is in the PHP manual.
- mathematical functions:
function SomeMaths($x)
{
return $x + pow($x, 3.2) - cos($x);
}
- functions which retrieve content from a file:
function GetConfiguration()
{
return parse_ini_file('configuration.ini');
}
- functions which retrieve content from a database:
function GetArticleById($id)
{
$sqlId = mysql_real_escape_string($id);
$result = mysql_query("SELECT `id`, `title` FROM `article` WHERE `id` = '$sqlId' LIMIT 1");
if (FALSE === $result)
{
throw new Exception('Query failed.');
}
return mysql_fetch_assoc($result);
}
If your project holds a function like one of these, and:
- your prefered profiling tool reveals that a lot of the execution time is spent in this function
- its returned value is always the same during a single run (script execution), when providing the same arguments
- this function is called more than once per run
Then consider caching (saving) its return values.
Here is how it can be achieved (yes, there are more advanced techniques to do it, but this is not the point of this post): add a static variable in the body of the function, which will hold an associative array, mapping every parameter combination with a return value:
function GetArticleById($id)
{
static $cache = array();
// Return value is not in cache yet?
if (!isset($cache[$id]))
{
$sqlId = mysql_real_escape_string($id);
$result = mysql_query("SELECT `id`, `title` FROM `article` WHERE `id` = '$sqlId' LIMIT 1");
if (FALSE === $result)
{
throw new Exception('Query failed.');
}
// Add return value to cache
$cache[$id] = mysql_fetch_assoc($result);
}
// Return cache content
return $cache[$id];
}
Here it is, the (possibly heavy) process of querying the database will only be executed once at the first function call. Every other function call with the same argument will use the cached return value.
Keep in mind that the amount of cached return values must be reasonable (available memory is limited). If there are millions of possible arguments combinations for a function in a single run, you’ll have to consider a more elaborate way of optimizing it (this could be the subject of a future post).
Also, always, always, ALWAYS profile your code BEFORE you decide to apply an optimization like this one (and wait for your project to be nearly completed before profiling).
]]>