0

I have an array populated by several class methods such that, I can randomly call some those methods for testing. The code below is what I'm trying to make work, but, I'm only getting the name of the method, it's not executed.

For example, lets say 1 is returned to $methodIndex, I get back func2() instead of Hello Func2.

Is there a function in PHP to do this or simple workaround?

class A{

    public function func1() { echo "Hello Func1"; }
    public function func2() { echo "Hello Func2"; }
    public function func3() { echo "Hello Func3"; }

    private $methods = ['func1', 'func2', 'func3'];

    public function get_methods(){ return $methods; }
}

$object = new A();

$methodIndex = mt_rand(0, count($object->get_methods()) - 1);
$object->get_methods()[$methodIndex]."()"; //e.g. $object->func2();
1

3 Answers 3

2

I think you're looking for call_user_func (short array syntax shown)

call_user_func([$object, $object->get_methods()[$methodIndex]]);
Sign up to request clarification or add additional context in comments.

Comments

0

It would be something along the lines of

$functionName = get_methods()[$methodIndex];
call_user_func(array($object, $functionName))

Comments

0

That's it :-)

class A{

    public function func1() { echo "Hello Func1"; }
    public function func2() { echo "Hello Func2"; }
    public function func3() { echo "Hello Func3"; }

    private $methods = ['func1', 'func2', 'func3'];

    public function get_methods(){ return $methods; }

    public function random(){
        $method = $this->methods[rand(0, (count($this->methods) - 1))];

        if(is_callable(array($this, $method))){
            return call_user_func_array(array($this, $method), func_get_args());
            }
        }
    }

$object = new A();

$object->random();

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.