0

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

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.