Jump to content

Recommended Posts

I have a question:

 

I read on this:

http://my.php.net/manual/en/function.call-user-func.php

 

The doc said, if there is any problem on calling the user's function, it will return false. So i put this:

$return_val = @call_user_func('my_function');

 

if($return_val === false) { die("ERROR!"); }

 

How if my function is returning a boolean?

function my_function() {

  if (//some expression here...) { return false; }

}

 

It is not calling error. My function is just returning an false bool value. How am I going to know it is error or returning value?

Link to comment
https://forums.phpfreaks.com/topic/166496-solved-php-call_user_func/
Share on other sites

Then you can use reflection. This should work:

 

<?php
function callFunction($callback, array $arguments = array())
{
if (is_array($callback)) {
	if (count($callback) == 2 && (is_string($callback[0]) || is_object($callback[0]) && is_string($callback[1]))) {
		$class = is_object($callback[0]) ? get_class($callback[0]) : $callback[0];
		$function = $callback[1];

		$reflection = new ReflectionMethod($class, $function);
	}
	else {
		throw new InvalidArgumentException('Invalid callback');
	}
}
else {
	$reflection = new ReflectionFunction($callback);

}

$params = $reflection->getParameters();
foreach ($params as $i => $param) {
	if (!$param->isOptional() && !isset($arguments[$i])) {
		throw new RuntimeException('Missing required argument ' . ($i + 1));
	}
}

if (is_array($callback)) {
	if (!is_object($callback[0]) && !$reflection->isStatic()) {
		throw new RuntimeException('Cannot statically call a non-static method');
	}
	else if (!is_object($callback[0])) {
		return call_user_func_array($callback, $arguments);
	}
	else {
		$return = $reflection->invokeArgs($callback[0], $arguments);
	}
}
else {
	$return = $reflection->invokeArgs($arguments);
}

return $return;
}

 

The $callback supports the regular callback format except the Class::method() notation.

 

Exceptions are good because they can be caught. Errors cannot easily be caught.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.