This just for fun script…
Imagine when we create a mockup for front end script that use a back end class which the methods are not yet to be ready… After a while, back and forth changing editor’s tabs just to create an empty method in that class, we start wondering (thus make the title The Wonder Method) if there some mechanism to call the yet nonexistence method from our script… heck, I even want return value from it!! and as a bonus, execute it when it ready… is it too trivial? but there have to be! it’s php! or is it already something built-in? but anyway, now we have!
It make use the officially magic method __call in php that triggered when invoking inaccessible methods in an object context. Below is the example:
<?php
class Animal
{
function __call($name, $arguments) {
if(substr($name, 0, 5) == 'call_'){
$name = substr($name, 5);
if(method_exists($this, $name)){
return call_user_func_array(array($this, $name), $arguments);
}
else{
$argc = count($arguments);
if($argc > 0){
return $arguments[$argc - 1];
}
return null;
}
}
else{
trigger_error("Fatal error: Call to undefined method $name", E_USER_ERROR);
}
}
}
$animal = new Animal();
$type = 'dog';
echo $animal->call_showSound($type, 'the dog is barking wuff wuff (imaginary result)').'<br />';
?>
Here, we will havebelow as the result:
the dog is barking wuff wuff (imaginary result)
now add following method when we ready to made changes to the class:
public function showSound($type)
{
switch($type){
case 'dog': return "the dog is barking wuff wuff (real result)";
case 'cat': return "the cat is miauwing miauwww (real result)";
}
return 'unknown animal (real result)';
}
Here, it should be return like this:
the dog is barking wuff wuff (real result)
Description, first in the __call method body, we inspect whether there are call to specific method name pattern for this wonder method we defined ourself (call_xxxxxx).
If the method is not existed yet, it will return the last argument as the mockup result from the real method later. As the method has exists, it will executed it and simulate a normal method call from the script. The wonder method name pattern can be useful when we want to keep track for clean up the code later.
I will left the implementation of this wonder thingy for what you think best… my guess, by not implement it at all…
Ok, that’s just about it! Happy coding everyone…