如何将PHP变量的值转换为字符串?
我正在寻找比连接一个空字符串更好的东西:
$myText = $myVar . '';
类似于Java或。net中的ToString()方法。
如何将PHP变量的值转换为字符串?
我正在寻找比连接一个空字符串更好的东西:
$myText = $myVar . '';
类似于Java或。net中的ToString()方法。
当前回答
This can be difficult in PHP because of the way data types are handled internally. Assuming that you don't mean complex types such as objects or resources, generic casting to strings may still result in incorrect conversion. In some cases pack/unpack may even be required, and then you still have the possibility of problems with string encoding. I know this might sound like a stretch but these are the type of cases where standard type juggling such as $myText = $my_var .''; and $myText = (string)$my_var; (and similar) may not work. Otherwise I would suggest a generic cast, or using serialize() or json_encode(), but again it depends on what you plan on doing with the string.
主要的区别在于,Java和. net在处理二进制数据和基本类型以及从特定类型转换到/从特定类型转换到字符串方面有更好的功能,即使对用户抽象了特定的情况也是如此。PHP的情况则完全不同,即使是处理十六进制也会让你摸不着头脑,直到你掌握了它。
我想不出更好的方法来回答这个问题,这是可比Java/。NET中的_toString()和此类方法通常以特定于对象或数据类型的方式实现。在这种情况下,神奇的方法__toString()和__serialize()/__unserialize()可能是最好的比较。
还要记住,PHP没有基本数据类型的相同概念。从本质上讲,PHP中的每一种数据类型都可以被认为是一个对象,它们的内部处理程序试图使它们具有某种通用性,即使这意味着在将float转换为int时失去准确性。你不能像在Java中那样处理类型,除非你在本地扩展中使用它们的zvals。
While PHP userspace doesn't define int, char, bool, or float as an objects, everything is stored in a zval structure which is as close to an object that you can find in C, with generic functions for handling the data within the zval. Every possible way to access data within PHP goes down to the zval structure and the way the zend vm allows you to handles them without converting them to native types and structures. With Java types you have finer grained access to their data and more ways to to manipulate them, but also greater complexity, hence the strong type vs weak type argument.
这些链接可能会有帮助:
https://www.php.net/manual/en/language.types.type-juggling.php https://www.php.net/manual/en/language.oop5.magic.php
其他回答
您还可以使用var_export PHP函数。
我认为值得一提的是,你可以通过使用输出缓冲来捕获变量中的任何输出(如print_r, var_dump):
<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>
感谢: 如何将var_dump的结果捕获到字符串?
文档说你还可以这样做:
$str = "$foo";
和演员一样,但是我觉得看起来更漂亮。
来源:
俄罗斯 英语
我如何转换一个PHP的值 变量转换为字符串?
可以使用(string)强制转换或strval()函数将值转换为字符串。(编辑:托马斯也说过)。
当您将它作为字符串使用时,它也应该自动为您强制转换。
除了Thomas G. Mayfield给出的答案之外:
如果你跟随字符串强制转换手册的链接,有一个非常重要的特殊情况需要理解:
(string)类型转换更可取,特别是如果变量$a是一个对象,因为PHP将根据其对象模型调用__toString()魔术方法来遵循类型转换协议(如果在$a实例化的类中定义了此方法)。
PHP做了类似的事情
function castToString($instance)
{
if (is_object($instance) && method_exists($instance, '__toString')) {
return call_user_func_array(array($instance, '__toString'));
}
}
(string)强制转换操作是PHP5+编程中推荐的技术,可以使代码更加面向对象。在我看来,这是一个与其他OOP语言(如Java/ c#等)设计相似(不同)的好例子。也就是说,以它自己特殊的PHP方式(只要是为了好的或有价值的)。