Home > php教程 > php手册 > PHP如何实现定义对象类型的常量

PHP如何实现定义对象类型的常量

WBOY
Release: 2016-06-06 19:35:25
Original
1016 people have browsed it

正常的直接define()一个对象,是回报错的,但我们查看PHP源码,可以发现除了数组不允许外,其他类型都可以用来定义常量,只不过对象的话要转化。 我们只需使用tostring方法即可。 无 repeat:switch (Z_TYPE_P(val)) {case IS_LONG:case IS_DOUBLE:case IS_STR

正常的直接define()一个对象,是回报错的,但我们查看PHP源码,可以发现除了数组不允许外,其他类型都可以用来定义常量,只不过对象的话要转化。
我们只需使用tostring方法即可。
repeat:
	switch (Z_TYPE_P(val)) {
		case IS_LONG:
		case IS_DOUBLE:
		case IS_STRING:
		case IS_BOOL:
		case IS_RESOURCE:
		case IS_NULL:
			break;
		case IS_OBJECT:
			if (!val_free) {
				if (Z_OBJ_HT_P(val)->get) {
					val_free = val = Z_OBJ_HT_P(val)->get(val TSRMLS_CC);
					goto repeat;
				} else if (Z_OBJ_HT_P(val)->cast_object) {
					ALLOC_INIT_ZVAL(val_free);
					if (Z_OBJ_HT_P(val)->cast_object(val, val_free, IS_STRING TSRMLS_CC) == SUCCESS) {
						val = val_free;
						break;
					}
				}
			}
			/* no break */
		default:
			zend_error(E_WARNING,"Constants may only evaluate to scalar values");
			if (val_free) {
				zval_ptr_dtor(&val_free);
			}
			RETURN_FALSE;
	}
Copy after login
Class Test{
   public $name='呵呵';
   public function __toString(){
     return $this->name;
   }
}

$t=new Test();
define('TT',$t);
echo TT;
Copy after login
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template