0

I am trying to call multiple arguments from a function in php using an array.

Class useful {
    function callFunctionFromClass($className, $function, $args = array()) {
            return $className::$function($args);
     }
}

<?php
    require("library/class.php");

    $u = new useful;

    $u::callFunctionFromClass(new useful, "text", "Test", "Test");
?>

I have the function text() created aswell like so:

function text($msg, $msg2) {
    echo $msg;
    echo $msg2;
}

I am getting this error message:

Warning: Missing argument 2 for useful::text(), 
  called in htdocs\class\library\class.php on line 16 
  and defined in htdocs\class\library\class.php on line 11
Test
Notice: Undefined variable: msg2 in htdocs\class\library\class.php on line 13

This works fine without $msg2 & a second argument. So how is multiple arguments pulled off?

1
  • You are calling a non-static class as a static class $u::callFunctionFromClass(new useful, "text", "Test", "Test"); that should be reporting an error also Commented Jul 30, 2015 at 13:50

1 Answer 1

3

you must use call_user_func_array. Also you are calling callFunctionFromClass as a static method but it isn't static

Class useful
{
    public function callFunctionFromClass($className, $function, $args = array())
    {
        return call_user_func_array(array($className, $function), $args);
    }

    public function text($msg, $msg2)
    {
        echo $msg;
        echo $msg2;
    }
}

$u = new useful;

$test = $u->callFunctionFromClass('useful', "text", array("Test", "Test"));
Sign up to request clarification or add additional context in comments.

2 Comments

Fixed it, just got rid of var_dump() and used it like I was earlier, Thanks!
that's because the method text is not returning anything.. you must use return inside the text method in order to have something returned

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.