Skip to content

Latest commit

 

History

History
83 lines (62 loc) · 1.78 KB

10.5.md

File metadata and controls

83 lines (62 loc) · 1.78 KB

10.5 PHP中的面向对象(一)

PHP7中的异常与PHP5略有不同,PHP7中新添加了一类Error。所以PHP7即可以抛出异常,又可以抛出错误。

API

ZEND_API ZEND_COLD zend_object *zend_throw_exception(
    zend_class_entry *exception_ce, 
    const char *message, 
    zend_long code);

ZEND_API zend_class_entry *zend_exception_get_default(void)
{
	return zend_ce_exception;
}
/* }}} */

/* {{{ Deprecated - Use zend_ce_error_exception directly instead */
ZEND_API zend_class_entry *zend_get_error_exception(void)
{
	return zend_ce_error_exception;
}

ZEND_API ZEND_COLD void zend_throw_error(zend_class_entry *exception_ce, const char *format, ...);

示例: 抛出异常

function test($val)
{
    throw new Exception("only for test exception");
    //'do nothing';
}
#include "zend_exceptions.h"//需要引入这个

PHP_METHOD(TEST_NAME, test)
{
    zend_throw_exception(zend_ce_exception, "only for test exception", 0 );
    //zend_throw_exception(NULL, "only for test", 0 );//同上
}

示例抛出错误

function test($val)
{
    throw new Error("only for test error");
    //'do nothing';
}
PHP_METHOD(TEST_NAME, test)
{
    zend_throw_error(zend_ce_error, "only for test error" );
    //zend_throw_error(NULL, "only for test erro");//这里的第一个参数可以指定为NULL,默认会使用zend_ce_error
}

开发者亦可抛出自定义的异常类如yaf中:

void yaf_throw_exception(long code, char *message) {
	zend_class_entry *base_exception = yaf_exception_ce;

	if ((code & YAF_ERR_BASE) == YAF_ERR_BASE
			&& yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(code)]) {
		base_exception = yaf_buildin_exceptions[YAF_EXCEPTION_OFFSET(code)];
	}

	zend_throw_exception(base_exception, message, code);
}