Home  >  Article  >  Backend Development  >  PHP中各种数据类型的区别和转换方法

PHP中各种数据类型的区别和转换方法

WBOY
WBOYOriginal
2016-06-23 13:28:571100browse

PHP本身可以通过隐式类型转换和显式类型转换两种方式来实现:
1. 隐式类型转换


例如

<?php $a = 7;$b = 'abcdsfdf';echo $a . $b;?>



在这里 $a 就被隐式的转化成了字符串,源码实现如下

if (UNEXPECTED(Z_TYPE_P(op1) != IS_STRING)) {if (Z_ISREF_P(op1)) {   op1 = Z_REFVAL_P(op1);if (Z_TYPE_P(op1) == IS_STRING) break;}ZEND_TRY_BINARY_OBJECT_OPERATION(ZEND_CONCAT, concat_function);use_copy1 = zend_make_printable_zval(op1, &op1_copy);



2. 显式类型转换


例如
<?php $double = 5.2323;echo (int)$double;?>


此时$double被强制转化为整形,该函数的实现是由源码中convert_to一系列方法实现的。
例如:ZEND_API void ZEND_FASTCALL _convert_to_string(zval *op ZEND_FILE_LINE_DC)

除此之外,还可以用

bool settype ( mixed &$var , string $type )函数来实现变量类型转化,源码实现如下:

PHP_FUNCTION(settype){    zval *var;    char *type;    size_t type_len = 0;    if (zend_parse_parameters(ZEND_NUM_ARGS(), "zs", &var, &type, &type_len) == FAILURE) {        return;    }    ZVAL_DEREF(var);    if (!strcasecmp(type, "integer")) {        convert_to_long(var);    } else if (!strcasecmp(type, "int")) {        convert_to_long(var);    } else if (!strcasecmp(type, "float")) {        convert_to_double(var);    } else if (!strcasecmp(type, "double")) { /* deprecated */        convert_to_double(var);    } else if (!strcasecmp(type, "string")) {        convert_to_string(var);    } else if (!strcasecmp(type, "array")) {        convert_to_array(var);    } else if (!strcasecmp(type, "object")) {        convert_to_object(var);    } else if (!strcasecmp(type, "bool")) {        convert_to_boolean(var);    } else if (!strcasecmp(type, "boolean")) {        convert_to_boolean(var);    } else if (!strcasecmp(type, "null")) {        convert_to_null(var);    } else if (!strcasecmp(type, "resource")) {        php_error_docref(NULL, E_WARNING, "Cannot convert to resource type");        RETURN_FALSE;    } else {        php_error_docref(NULL, E_WARNING, "Invalid type");        RETURN_FALSE;    }    RETVAL_TRUE;}

版权声明:本文为博主原创文章,未经博主允许不得转载。

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