I have been looking at different languages to get started. I found method_missing in Ruby very interesting but was not able to find the same in Java and PHP. Is there something like method_missing in Java or PHP ?
PHP has __call($name, array $args)
. It is a catchall which handles situations where you call a method which is not defined for the instance.
In PHP >= 5.3 there is also __callStatic($name, array $args)
which functions largely the same way only on the class level (duh).
class MyClass
{
public function __call($name, array $args)
{
echo "You tried to call $name(".implode(',',$args)."). Silly user.";
}
}
$k = new MyClass();
$k->doSomething(1,2,3); // You tried to call doSomething(1,2,3). Silly user.
The equivalent in Java is a bit more cumbersome and it involves something called the Proxy class. A tutorial can be found here -- the examples are a bit much to summarize here.
In PHP, you can use the magic method __call()
.
In Java you might be able to do something with an interface, a Proxy and reflection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With