tags:

views:

163

answers:

2

hello I have this PHP class

   class myclass{
       function name($val){
           echo "this is name method and the value is".$val;
       }

       function password($val){
           echo "this is password method and the value is".$val;
       }
   }

and here is how to use it:

  $myclass= new myclass();
  $myclass->name("aaa")//output: this is name method and the value is aaa

it works fine because I just have 2 methods "name" and "password" what If I have a huge number of methods, it would not be easy to add those methods to my class and write the same code for each method, I want to change my class to let each method give the same output apart from the method name? and I don't want to write all details for all methods because they are almost similar,is this possible in PHP? I wish I was clear :)

+13  A: 

You could override the __call() method for the class, which is a "magic method" that will be used when a non-existent method is called.

Rob
+3  A: 

Use the __call magic method, like the following:

class myclass
{
    function __call($func, $args)
    {
        echo 'this is ', $func,  'method and the value is', join(', ', $args);
    }
}

This function will get called for any function that doesn't have an explicit function definition.

Note that $args is an array containing all the parameters the function's called with.

Ciaran McNulty