1

I have a problem in calling a function that the name is being stored in an array.

class tempClass {
   function someFunction() {
      $tempArray = array('functionName' => 'tempFunction');
      $tempArray['functionName']();
   }

   function tempFunction() {
      echo "inside function";
   }
}

It gives me an error:

"Fatal error: Call to undefined function tempFunction() in /..... line..".

Line number is the line where the function is being called, $tempArray['functionName']();

But if called the method_exists(), it shows that the method is exists. It is very confusing. Can anyone please help me out? Thanks.

1

2 Answers 2

4

Use call_user_func() , like this:

call_user_func($tempArray['functionName']);

UPDATE:
As you want to call a method of a class from inside that class, use the following instead:

call_user_func(array($this, $tempArray['functionName']));

See working demo

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

7 Comments

I got this error "Warning: call_user_func() expects parameter 1 to be a valid callback, function 'tempFunction' not found or invalid function name in...."
Same problem as with your original attempt: you are missing the scope.
yes you are right, How stupid of me. I used $this->$tempArray['functionName'](); and it worked. Thanks a lot guys.
@AbhishekSalian I've updated my answer with a corrected version for your case (calling a method of the class from within the class), check it out.
@arkascha Yes I didn't notice it first time, check out my update for the fixed version.
|
2

Well you ask if the method exists inside the class or object, but you call it without that scope. That won't work...

Try this instead:

call_user_method($tempArray['functionName'],$this);

Just saw that call_user_method() is depreciated. Use call_user_func() as answered by Nelson instead.

3 Comments

it didnt work with the above cmd but i just added the scope to the calling function. thanks.
This answer does not work, the error can be seen here codepad.org/CIT7IDhT
@Nelson: that is true, sorry for that. I corrected the answer, but Nelsons answer is better: just saw that call_user_mothod is depreciated! Sorry for the confusion.

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.