【问题标题】:Is there a way to check if a function exists within a class?有没有办法检查一个函数是否存在于一个类中?
【发布时间】:2013-12-11 05:54:39
【问题描述】:

我正在传递一些帖子数据以执行基于帖子数据的函数,以确定是否应该执行我尝试使用以下内容:

$SP = new StoredProcedure();

if(function_exists($SP->$_POST['function']))
{
    $SP->$_POST['function']();
}
else
{
    echo 'function does not exist.';
}

不幸的是,这传递了以下错误:

注意:未定义的属性:StoredProcedure::$getFormList in C:\DWASFiles\Sites\junglegym\VirtualDirectory0\site\wwwroot\wp-content\plugins\qcore\qcore_waitress.php 353行的函数不存在。

我确定这个函数确实存在,当我在没有function_exists()的情况下执行它时

有没有办法检查类中的函数是否存在?

【问题讨论】:

    标签: php function


    【解决方案1】:

    method_exists 检查给定对象的类的方法:

    文档链接: http://www.php.net/method_exists

    if(method_exists($SP, $_POST['function'])) {
        {
            $SP->$_POST['function']();
        }
        else
        {
            echo 'function does not exist.';
        }
    

    function_exists()method_exists() 用于这些检查。第一个用于常规函数,第二个用于OOP 函数。

    【讨论】:

      【解决方案2】:

      你应该使用method_exists

      尝试:

      if(method_exists($SP, $_POST['function'])) {
      

      【讨论】:

      • 太棒了!非常感谢!
      【解决方案3】:

      全部检查

      Find out if a method exists in a static class

      Checking if function exists

      还有 PHP 手册在

      php.net/method_exists

      php.net/manual/en/function.function-exists.php

      www.php.net/class_exists

      希望这些对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-21
        • 2010-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-21
        • 2015-02-14
        • 1970-01-01
        相关资源
        最近更新 更多