views:

525

answers:

3

Hi,

I have a class 'abc', with several functions inside it: 'abc_function1' 'abc_function2' 'abc_function3' 'abc_function4' 'abc_function5'

I would like to call a function of the class 'abc' according to a parameter that I enter, a string containing 'function1' or 'function 4' for example, to refer to the corresponding function of the class.

I hope I've made myself clear ;)

Thanks a lot for your help

A: 
$class_instance = new class();
call_user_func( 
   array( $class_instance, $your_string_containing_the_fx_name ), 
   $the_parameters_you_want_to_pass
);
lemon
+3  A: 

Not exactly sure why but this has a certain code smell in my opinion. But anyway...

Method a): Implement the "magic" method __call($name, $params).

<?php
class Foo {
  public function abc_function1() {
    echo "function #1";
  }

  public function abc_function2() {
    echo "function #2";
  }

  public function abc_function3() {
    echo "function #3";
  }

  public function __call($name, $params) {
    $fqn = 'abc_'.$name;
    if ( method_exists($this, $fqn) ) {
      call_user_func_array( array($this, $fqn), $params);
    }
  }
}

$f = new Foo;
$f->function2();

Method b): Same idea, just without the automagical mapping.

<?php
class Foo {
  public function abc_function1() {
    echo "function #1";
  }

  public function abc_function2() {
    echo "function #2";
  }

  public function abc_function3() {
    echo "function #3";
  }

  public function doSomething($x, $y, $z) {
    $fqn = 'abc_'.$x;
    if ( method_exists($this, $fqn) ) {
      call_user_func_array( array($this, $fqn), array($y, $z));
    }
  }
}

$f = new Foo;
$f->doSomething('function2', 1, 2);

Method c) If you know the number of parameter you can also use

$this->$fqn($,y, $z)

instead of

call_user_func_array( (array($this, $fqn), array($y, $z) );

see also: http://docs.php.net/call_user_func_array and http://docs.php.net/functions.variable-functions

VolkerK
A: 

You can use the variable functions feature of PHP:

function call_function( $string ) {
    $var = 'abc_' . $string;
    $retval = $var(); // this will call function named 'abc_'
                      // plus the contents of $string
    return $retval;
}
Anax