Q:

php class function -> call the function according to a passing parameter

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:

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

