Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method missing in Java or PHP

Tags:

java

php

ruby

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 ?

like image 732
user914312 Avatar asked Aug 26 '11 14:08

user914312


3 Answers

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.

like image 120
cwallenpoole Avatar answered Oct 03 '22 13:10

cwallenpoole


In PHP, you can use the magic method __call() .

like image 32
xdazz Avatar answered Oct 03 '22 12:10

xdazz


In Java you might be able to do something with an interface, a Proxy and reflection.

like image 26
Bart van Heukelom Avatar answered Oct 03 '22 13:10

Bart van Heukelom