PHP equivalent of .NET/Java's toString()

2019-01-02 16:54发布

How do I convert the value of a PHP variable to string?

I was looking for something better than concatenating with an empty string:

$myText = $myVar . '';

Like the ToString() method in Java or .NET.

标签: php string
24条回答
零度萤火
2楼-- · 2019-01-02 17:08

PHP is dynamically typed, so like Chris Fournier said, "If you use it like a string it becomes a string". If you're looking for more control over the format of the string then printf is your answer.

查看更多
唯独是你
3楼-- · 2019-01-02 17:09

Putting it in double quotes should work:

$myText = "$myVar";
查看更多
弹指情弦暗扣
4楼-- · 2019-01-02 17:10

For objects, you may not be able to use the cast operator. Instead, I use the json_encode() method.

For example, the following will output contents to the error log:

error_log(json_encode($args));
查看更多
宁负流年不负卿
5楼-- · 2019-01-02 17:12

Some if not all of the methods above fail when the intended string variable has a leading zero ie 077543 an attempt to convert such a variable fails to get the intended string because the variable is converted to base 8 (octal).

All these will make $str have a value of 32611

$no = 077543  
$str = (string)$no;   
$str = "$no";   
$str = print_r($no,true);  
$str = strval($no);   
$str = settype($no, "integer");  
查看更多
明月照影归
6楼-- · 2019-01-02 17:15

In addition to the answer given by Thomas G. Mayfield:

If you follow the link to the string casting manual, there is a special case which is quite important to understand:

(string) cast is preferable especially if your variable $a is an object, because PHP will follow the casting protocol according to its object model by calling __toString() magic method (if such is defined in the class of which $a is instantiated from).

PHP does something similar to

function castToString($instance) 
{ 
    if (is_object($instance) && method_exists($instance, '__toString')) {
        return call_user_func_array(array($instance, '__toString'));
    }
}

The (string) casting operation is a recommended technique for PHP5+ programming making code more Object-Oriented. IMO this is a nice example of design similarity (difference) to other OOP languages like Java/C#/etc., i.e. in its own special PHP way (whenever it's for the good or for the worth).

查看更多
低头抚发
7楼-- · 2019-01-02 17:17

You can use also, var_export php function.

查看更多
登录 后发表回答