Home  >  Article  >  Backend Development  >  PHP Object-Oriented Programming and Design Patterns (4)_PHP Tutorial

PHP Object-Oriented Programming and Design Patterns (4)_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:28:36816browse

PHP Advanced Programming Study Notes 2014.06.12

Exceptions are often used to handle various types of errors encountered during normal program execution. For example, when doing database linking, you have to deal with database connection failure. Using exceptions can improve the fault tolerance of our programs, making our applications more stable and robust.

Usage exception

PHP5 adds exception handling modules similar to other languages. Exceptions generated in PHP code can be thrown by the throw statement and caught by the catch statement. Code that requires exception handling must be placed in a try code block to catch possible exceptions. Each try corresponds to at least one catch block. Use multiple catches to catch exceptions generated by different classes. When the try block no longer throws an exception or no catch is found that matches the thrown exception, the PHP code continues execution after jumping to the last catch. Of course, PHP allows exceptions to be thrown again within catch blocks.

Predefined exception Exception

The Exception class is the base class for all exceptions. We can derive custom exceptions by deriving the Exception class. The following list lists basic information about Exception.

<span>Exception</span><span> {

    </span><span>/*</span><span> 属性 </span><span>*/</span>
    <span>protected</span> <span>string</span> <span>$message</span> ;        <span>//</span><span>异常消息内容</span>
    <span>protected</span> int <span>$code</span> ;            <span>//</span><span>异常代码</span>
    <span>protected</span> <span>string</span> <span>$file</span> ;        <span>//</span><span>抛出异常的文件名</span>
    <span>protected</span> int <span>$line</span> ;            <span>//</span><span>抛出异常在该文件中的行号</span>

    <span>/*</span><span> 方法 </span><span>*/</span>
    <span>public</span> __construct ([ <span>string</span> <span>$message</span> = "" [, int <span>$code</span> = 0 [, <span>Exception</span> <span>$previous</span> = <span>NULL</span> ]]] )    <span>//</span><span>异常构造函数</span>
    <span>final</span> <span>public</span> <span>string</span> getMessage ( void )            <span>//</span><span>获取异常消息内容</span>
    <span>final</span> <span>public</span> <span>Exception</span> getPrevious ( void )        <span>//</span><span>返回异常链中的前一个异常</span>
    <span>final</span> <span>public</span> int getCode ( void )                <span>//</span><span>获取异常代码</span>
    <span>final</span> <span>public</span> <span>string</span> getFile ( void )            <span>//</span><span>获取发生异常的程序文件名称</span>
    <span>final</span> <span>public</span> int getLine ( void )                <span>//</span><span>获取发生异常的代码在文件中的行号</span>
    <span>final</span> <span>public</span> <span>array</span> getTrace ( void )            <span>//</span><span>获取异常追踪信息</span>
    <span>final</span> <span>public</span> <span>string</span> getTraceAsString ( void )    <span>//</span><span>获取字符串类型的异常追踪信息</span>
    <span>public</span> <span>string</span> __toString ( void )                <span>//</span><span>将异常对象转换为字符串</span>
    <span>final</span> <span>private</span> void __clone ( void )                <span>//</span><span>异常克隆</span>
}

After understanding Exception, let’s try to extend the exception class to implement a custom exception.

<span>function</span><span> connectToDatabase()
{    
    </span><span>if</span>(!<span>$link</span> = <span>mysql_connect</span>("myhost","myuser","mypassw","mybd"<span>))
    {
        </span><span>throw</span> <span>new</span> <span>Exception</span>("could not connect to the database."<span>);
    }
}

</span><span>try</span><span>
{
    connectToDatabase();
}
</span><span>catch</span>(<span>Exception</span> <span>$e</span><span>)
{</span><span>echo</span> <span>$e</span>-><span>getMessage();
}</span>

Here we throw an Exception type exception, catch this exception in catch, and finally print out "could not connect to the database.". Maybe you want to also display information about why the database connection failed. Next, we implement our custom information by extending the exception class.

<span>class</span> MyException <span>extends</span> <span>Exception</span><span>
{
    </span><span>protected</span> <span>$ErrorInfo</span><span>;

    </span><span>//</span><span>构造函里处理一些逻辑,然后将一些信息传递给基类</span>
    <span>public</span> <span>function</span> __construct(<span>$message</span>=<span>null</span>,<span>$code</span>=0<span>)
    {
        </span><span>$this</span>->ErrorInfo = '自定义错误类的错误信息'<span>;
        parent</span>::__construct(<span>$message</span>,<span>$code</span><span>);
    }    

    </span><span>//</span><span>提供获取自定义类信息的方法</span>
    <span>public</span> <span>function</span><span> GetErrorInfo()
    {
        </span><span>return</span> <span>$this</span>-><span>ErrorInfo;
    }

    </span><span>/*</span><span>*
     *
     *这里还可以添加异常日志,只需在上面的构造函数里调用就可以了
     *
     </span><span>*/</span>

    <span>public</span> <span>function</span> <span>log</span>(<span>$file</span><span>)
    {
        </span><span>file_put_contents</span>(<span>$fiel</span>,<span>$this</span>->__toString(),<span>FILE_APPEND);
    }
}

</span><span>function</span><span> connectToDatabase()
{    
    </span><span>throw</span> <span>new</span> MyException("ErrorMessage"<span>);
}

</span><span>try</span><span>
{    
    connectToDatabase();
}
</span><span>catch</span>(MyException <span>$e</span><span>)
{    
    </span><span>echo</span> <span>$e</span>->getMessage() . "\n"<span>;
    </span><span>echo</span> <span>$e</span>-><span>GetErrorInfo();
}</span>

set_exception_handler Set a user-defined exception handling function

The name of the function called when an uncaught exception occurs as a parameter to set_exception_handler. This function must be defined before calling set_exception_handler(). This function accepts one parameter, which is a thrown exception object. This can be used to improve the exception logging handling mentioned above.

<span>function</span> ExceptionLogger(<span>$exception</span><span>)
{
    </span><span>$file</span>='ExceptionLog.log'<span>;
    </span><span>file_put_contents</span>(<span>$fiel</span>,<span>$exception</span>->__toString(),<span>FILE_APPEND);
}

</span><span>set_exception_handler</span>(ExceptionLogger);

1.3. PHP allows exceptions to be thrown again within the catch code block.

<span>try</span><span>
{
    </span><span>#</span><span>code...</span>
<span>}
</span><span>catch</span>(<span>Exception</span> <span>$e</span><span>)
{
    </span><span>if</span>(<span>$e</span>->getCode() == 999<span>)
    {
        </span><span>#</span><span>进行一些操作</span>
<span>    }
    </span><span>else</span><span>
    {
        </span><span>throw</span> <span>$e</span><span>;
        
    }
}</span>

Summary

The exception function is very powerful, but it does not mean that we can abuse the exception mechanism wantonly in the project, especially the mechanism of extensive use of exception logs, which will greatly increase the system overhead and reduce the performance of the application. We can use error codes to easily manage error messages. When an error message is thrown multiple times, using error codes is a scientific choice. We can even use error codes to display error messages in multiple languages.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/781920.htmlTechArticlePHP Advanced Programming Study Notes 2014.06.12 Exceptions are often used to handle some problems encountered during the normal execution of the program. Various types of errors. For example, when doing database linking, you have to deal with data...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn