【问题标题】:Custom error message when calling a function that doesn't exist in a class调用类中不存在的函数时的自定义错误消息
【发布时间】:2014-09-01 16:52:54
【问题描述】:

我在 GitHub (link)* 上有一个类,如果指定的类不存在,我想输出一条自定义错误消息。这可能吗?例如:

用户尝试调用函数123456()不存在(main::123456())也不存在,输出错误信息:

抱歉,函数 123456 不存在或已被删除。

这可能吗?

*链接已不存在

【问题讨论】:

    标签: php function class


    【解决方案1】:

    您可以通过覆盖魔术方法__call() 来做到这一点。这样做时,您必须为方法提供两个参数(例如,$name$args),否则这将不起作用。

    class MyClass {
        public function __call($name, $arguments) {
            throw new Exception("failed to call method ".$name);
        }
        public function __callStatic($name, $arguments) {
            throw new Exception("failed to call static method ".$name);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-19
      • 2019-02-20
      • 2018-04-17
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多