0

I've custom code where I run class methods:

$object = new UserClass();
$method = 'create';
$params = ['name' => 'John'];

$reflectionMethod = new \ReflectionMethod($object, $method);

if($reflectionMethod->isStatic()) {
    return $object::$method($params);
} else {
    return $object->$method($params);
}

How I can run class method without checking if the method type is static or not, with one line if possible?

0

1 Answer 1

3
class UserClass {
    public static function foo(string $name) {
        echo 'hi ', $name, "\n";
    }

    public function bar(string $name) {
        echo "bye ", $name, "\n";
    }
}

$object  = new UserClass();
$methods = ['foo', 'bar'];


foreach ($methods as $method) {
    call_user_func([$object, $method], "Bobby");
}

Outputs:

hi Bobby
bye Bobby

call_user_func() does not care if the method is static or not. It work in both cases.

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

3 Comments

How to pass args then @yivi ?
Or call_user_func_array([ $object, $method ], $params );
Any arguments after the callable are passed to the called method.

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.