开发者

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

开发者 https://www.devze.com 2022-12-20 14:48 出处:网络
I have a class \'abc\', with several functions inside it: \'abc_function1\' \'abc_function2\' \'abc_function3\'

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

I would l开发者_运维百科ike 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


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


$class_instance = new class();
call_user_func( 
   array( $class_instance, $your_string_containing_the_fx_name ), 
   $the_parameters_you_want_to_pass
);


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号