php method to convert a variable into a string: first create a PHP sample file; then use the "function variable_to_string($variable){...}" method to convert a variable into a string string.
The operating environment of this tutorial: windows10 system, php5.6. This article is applicable to all brands of computers.
Recommended: "PHP Video Tutorial"
php Convert a variable to a string
The code is as follows:
/** * 将一个变量转为字符串 * float使用var_export得到的字符串不准确 * resource使用var_export得到的是null * @param $variable * @return string */ function variable_to_string($variable) { return is_float($variable) ? (string)$variable : ( is_resource($variable) ? "'resource of type'" : var_export($variable, true) ); } // int $a = 4; var_dump(variable_to_string($a)); /** * 输出:string(1) "4" */ // float $a = 100.4; var_dump(variable_to_string($a)); /** * 输出:string(5) "100.4" */ // string $a = 'abcdefg'; var_dump(variable_to_string($a)); /** * 输出:string(9) "'abcdefg'" */ // array $a = ['a' => 'a', 'b' => 'b']; var_dump(variable_to_string($a)); /** * 输出:string(37) "array ( * 'a' => 'a', * 'b' => 'b', * )" */ // object $a = new stdClass(); $a->a = 'a'; $a->b = 'b'; var_dump(variable_to_string($a)); /** * 输出:string(61) "stdClass::__set_state(array( * 'a' => 'a', * 'b' => 'b', * ))" */ // bool $a = false; var_dump(variable_to_string($a)); /** * 输出:string(5) "false" */ // null $a = null; var_dump(variable_to_string($a)); /** * 输出:string(4) "NULL" */ // resource $a = fopen('./test.log', 'wb+'); var_dump(variable_to_string($a)); /** * 输出:string(18) "'resource of type'" */
The above is the detailed content of How to convert variables to string in php. For more information, please follow other related articles on the PHP Chinese website!