Home  >  Article  >  Backend Development  >  How to convert variable to string in php

How to convert variable to string in php

(*-*)浩
(*-*)浩Original
2019-09-30 11:32:518776browse

PHP does not require (or support) explicit type definitions in variable definitions; the variable type is determined based on the context in which the variable is used.

How to convert variable to string in php

php can use (String) to force a variable into a string. A string string is composed of a series of characters, where each character is equivalent to One byte. (Recommended learning: PHP video tutorial)

/**
 * 将一个变量转为字符串
 *  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 variable to string in php. For more information, please follow other related articles on the PHP Chinese website!

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