提供对“呼叫”的被叫方响应;调用未定义的方法“;错误


Providing a callee response to a "call to undefined method" error?

我正在学习如何使用PHP进行更高级的编程。

我看到调用一个不存在的方法会产生"对未定义方法的调用"错误。

PHP非常灵活,有没有一种技术可以拦截这个错误?如果是,通常是如何做到的?

编辑:为了澄清,当错误发生时,我想做一些事情,比如发回回复,而不一定要阻止它。忘了提一下这是在类的上下文中。当然,方法只适用于类的上下文;)

是的,可以使用魔术方法捕获对类的未定义方法的调用:

您需要实现此处定义的__call()和/或__callStatic()方法。

假设您有一个简单的类CCalculationHelper,只有几个方法:

class CCalculationHelper {
  static public function add( $op1, $op2 ) {
    assert(  is_numeric( $op1 ));
    assert(  is_numeric( $op2 ));
    return ( $op1 + $op2 );
  }
  static public function diff( $op1, $op2 ) {
    assert(  is_numeric( $op1 ));
    assert(  is_numeric( $op2 ));
    return ( $op1 - $op2 );
  }
}

稍后,您需要通过乘法或除法来增强此类。您可以使用一种神奇的方法来实现这两种操作,而不是使用两种显式方法:

class CCalculationHelper {
  /**  As of PHP 5.3.0  */
  static public function __callStatic( $calledStaticMethodName, $arguments ) {
    assert( 2 == count( $arguments  ));
    assert( is_numeric( $arguments[ 0 ] ));
    assert( is_numeric( $arguments[ 1 ] ));
    switch( $calledStaticMethodName ) {
       case 'mult':
          return $arguments[ 0 ] * $arguments[ 1 ];
          break;
       case 'div':
          return $arguments[ 0 ] / $arguments[ 1 ];
          break;
    }
    $msg = 'Sorry, static method "' . $calledStaticMethodName . '" not defined in class "' . __CLASS__ . '"';
    throw new Exception( $msg, -1 );
  }
  ... rest as before... 
}

这样说吧:

  $result = CCalculationHelper::mult( 12, 15 );

看到您不希望从这些致命错误中恢复,您可以使用关闭处理程序:

function on_shutdown()
{
    if (($last_error = error_get_last()) {
        // uh oh, an error occurred, do last minute stuff
    }
}
register_shutdown_function('on_shutdown');

无论是否发生错误,函数都会在脚本结束时调用;则对CCD_ 4进行调用以确定这一点。

如果你的意思是如何拦截自定义类中不存在的方法,你可以做这样的

<?php
    class CustomObject {
        public function __call($name, $arguments) {
            echo "You are calling this function: " . 
            $name . "(" . implode(', ', $arguments) . ")";
        }
    }
    $obj = new CustomObject();
    $obj->HelloWorld("I love you");
?>

或者如果你想截获的所有错误

function error_handler($errno, $errstr, $errfile, $errline) {
    // handle error here.
    return true;
}
set_error_handler("error_handler");