How to convert variable to string in php

(*-*)浩
Release: 2023-02-25 17:20:01
Original
8779 people have browsed it

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'"
 */
Copy after login

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!

Related labels:
php
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!