如何检查函数是否作为参数传递


How do I check if a function is being passed as a parameter?

问题:

如何检查函数是否作为参数传递

特别是如果传递的函数返回字符串等?

IE在下面的例子中,我不想htmlentities作为参数传递的函数html,但我确实想htmlantities其他任何东西。还假设以后可能有多个参数需要执行一个函数。

示例:

function html($tag,$content)
{
if(!is_callable($content)){$var=htmlentities($var, ENT_NOQUOTES, "UTF-8");}
return "<".$tag.">".$content."</".$tag.">";
}

echo html(html('Example','Example'),'Example');

这个例子似乎对我不起作用。当它是一个函数时,我仍然会得到htmlentited内容。

虽然无法检测传递给函数的字符串是否是另一个函数的结果,但您可以传递一些不是字符串但行为类似字符串的东西。

虽然我并不建议这样做,而且副作用可能很多,但这里有一个可能的解决方案。

一个助手类,它假装是一个字符串,但它是一个类。

class sillyString
{
    private $string = '';
    public function __construct($string)
    {
        $this->string = $string;
    }
    public function __toString()
    {
        return $this->string;
    }
}

你的职能。我对它做了一些调整,但它会检查内容的类型。

function html($content, $tag)
{
    if (!is_object($content)) {
        $content = htmlentities($content, ENT_NOQUOTES, "UTF-8");
    }
    return new sillyString("<".$tag.">".$content."</".$tag.">");
}

像以前一样调用函数。

print html(html('content','tag1'),'tag2');

因此,函数现在可以判断您没有传递字符串,但您仍然可以像函数中的字符串一样使用它。

根据我在您的示例中所看到的,实现您想要的目标的最佳方法是第三个参数$escape_var:

function foo( $var, $var2, $escape_var = true)
{
    if( $escape_var === true)
        $var = htmlentities( $var, ENT_NOQUOTES, "UTF-8");
    return $var." ".$var2;
}
echo foo(foo('<Example>','<Example>'),'<Example>', false);

不,您不能检查,您没有传递函数,只是超过了函数的返回值。

相反,您可以根据自己的需要执行以下操作。

function foo() {
  $vars = func_get_args();
  foreach ($vars as &$var) {
    $var = htmlentities($var, ENT_NOQUOTES, "UTF-8");
  }
  return implode(" ", $vars);
}
// usage
foo('<Example>', '<Example>', '<Example>');