【问题标题】:function_exists returns false every timefunction_exists 每次都返回 false
【发布时间】:2012-03-08 12:00:01
【问题描述】:

我正在尝试检查一个函数是否存在,但我的 if 总是出错

我尝试这样调用函数,其中$function是函数名

if (function_exists($this->module->$function))
{
    $this->module->$function($vars);
}
else
{
    echo 'no';
}

变量module被定义为函数应该被调用的类:

$this->module = $module;
$this->module = new $this -> module;

我在这里遗漏了什么吗? 谢谢!

【问题讨论】:

    标签: php oop function


    【解决方案1】:

    只是可以弄清楚: 使用method_exists() 解决了我的问题

    method_exists($this->module,$function)
    

    我自己为可能有同样问题的人回答了这个问题!

    【讨论】:

      【解决方案2】:

      你需要使用method_exists():

      if (method_exists($this->module, $function)) {
          // do stuff
      }
      

      【讨论】:

        【解决方案3】:

        你需要检查方法是否存在而不是函数:

        if (method_exists($this->module, $function))
        {
            $this->module->$function($vars);
        }
        else
        {
            echo 'no';
        }
        

        查看文档:http://php.net/manual/en/function.method-exists.php

        【讨论】:

          【解决方案4】:

          function_exists将函数名作为字符串,没有类层次的概念。

          如果$function是函数名,只需使用以下代码:

          if(function_exists($function)) {
              // Call $function().
          }
          

          但是,查看您的代码看起来更像是您想要检测对象的方法是否存在。

          method_exists 有两个参数,1:要测试的对象,2:要检测的方法的名称。

          if(method_exists($this->module, $function)) {
              $this->module->$function($vars);
          }
          

          【讨论】:

            【解决方案5】:

            function_exists() 需要一个字符串作为参数。这样就可以了:

            method_exists($this->module, $function);
            

            祝你好运!

            【讨论】:

              猜你喜欢
              • 2015-08-21
              • 2017-08-26
              • 1970-01-01
              • 2022-12-14
              • 2015-01-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多