set_error_handler()收到无效的回调?

时间:2016-05-05 04:06:37

标签: php error-handling callback

我收到此错误:

  

set_error_handler()期望参数(userErrorAdvice)是有效的回调

trait userErrorAdviceTrait
{
    public function userErrorAdvice()
    {
        $error = error_get_last();
        $_SESSION['errorStore'] = $error;
        $errorMessage = "No file exists for the PageController";
        if (strstr($error['message'], "No file exists for the PageController class"))
        {
            header('Location: http://192.171.127.39/~louis/errorAdvicePage.php?errorType=NoPageControllerError');
            exit;
        }
    }
    public function setUserErrorAdvice()
    {
        set_error_handler("userErrorAdvice");
    }
}
use userErrorAdviceTrait;
public static function makePageController($pageName) 
{
    //self::shutDownFunction();
    //self::shutdown_function();
    self::setUserErrorAdvice();

    //Rest of code .... 

这迫使我写更多详情,但我没有什么可说的。

1 个答案:

答案 0 :(得分:1)

我为此做了一个简单的工作测试。这是我要审核的代码

<?php

trait userErrorAdviceTrait
{
    public function function userErrorAdvice($errno, $errstr)
    {
        echo 'error no '.$errno.' and message '.$errstr.PHP_EOL;
    }

    public function setUserErrorAdvice()
    {
        set_error_handler("userErrorAdvice");
    }
}

class TestErrorFunction
{
    use userErrorAdviceTrait;

    public static function makePageController($pageName)
    {
        self::setUserErrorAdvice();
    }
}

TestErrorFunction::makePageController('page');

我在这里看到一些问题。让我解释一下并解决它们。

  1. 您使用非静态函数作为静态函数。当应该执行方法(函数)userErrorAdvice()时,它应该'具有'和对象。但是没有为该函数创建对象。

  2. set_error_handler()函数的参数应为PHP callable。在我们的例子中,没有全局函数userErrorAdvice()

  3. 有几种可能的方法可以解决问题。例如

    <?php
    
    trait userErrorAdviceTrait
    {
        public static function userErrorAdvice($errno, $errstr )
        {
            echo 'error no '.$errno.' and message '.$errstr.PHP_EOL;
        }
    
        public static function setUserErrorAdvice()
        {
            set_error_handler([userErrorAdviceTrait::class, "userErrorAdvice"]);
            // the other option here
            // set_error_handler('userErrorAdviceTrait::userErrorAdvice');
        }
    }
    
    class TestErrorFunction
    {
        use userErrorAdviceTrait;
    
        public static function makePageController($pageName)
        {
            self::setUserErrorAdvice();
            include 'no existing file';
        }
    }
    
    TestErrorFunction::makePageController('page');
    

    此代码产生以下输出。

    $ php code.php 
    error no 2 and message include(no existing file): failed to open stream: No such file or directory
    error no 2 and message include(): Failed opening 'no existing file' for inclusion (include_path='.:/usr/share/php')
    

    再一次我做了什么

    1. 修正了可调用参数。
    2. 将定义的方法定义为静态,因此它们在静态上下文中使用。
相关问题