我可以将变量类型从对象更改为字符串吗?

时间:2012-09-14 07:30:11

标签: php type-conversion

  

可能重复:
  how to convert object into string in php

我有一个包含某个对象的变量(SimpleXML) 我可以更改此变量的类型,并将其自身分配给此变量吗? 像这样:

$test = (string)$test;
var_dump($test);

上述代码不起作用,因此输出仍然是object(SimpleXMLElement)而不是string

但是当我为它分配另一个变量时,如$new_test = (string)$test它运行良好,var_dump输出为string]

5 个答案:

答案 0 :(得分:1)

这取决于SimpleXML如何实现魔术函数__toString()。它因班级而异。但如果没有实现,PHP将会抛出一个致命的错误。

因此,除非object方法已实施,否则直接从string__toString()的类型转换不起作用。

答案 1 :(得分:0)

如果您想要字符串内容,请使用asXML方法。

var_dump($test->asXML());

答案 2 :(得分:0)

你不能像添加一个声明那样将一个对象转换为字符串,它可能会工作,但它不会像预期的那样表现有一个greate文章虽然在这里写在堆栈中你应该如何做到最好的方式是通过添加一个tostring方法在这里阅读更多... how to convert object into string in php

答案 3 :(得分:0)

将SimpleXMLObject强制转换为字符串

$foo = array( (string) $xml->parent->child );

<?php
  $xmlstring = "<parent><child> hello world </child></parent>";
  $xml = simplexml_load_string($xmlstring);
  $foo = array( (string) $xml->child );
  var_dump($xml).PHP_EOL;
  var_dump($foo);
?>

输出

object(SimpleXMLElement)#1 (1) {
  ["child"]=>
  string(13) " hello world "
}
array(1) {
  [0]=>
  string(13) " hello world "
}

http://codepad.org/Bss1rndd

答案 4 :(得分:0)

这取决于被转换的对象。对于SimpleXML,您可能需要asXML方法:http://www.php.net/manual/en/simplexmlelement.asxml.php。对于常规对象,如果对象实现__toString()方法,则可以对字符串进行类型转换。另一种选择是var_export(...,true),但除了调试之外,这很少有用。