-1

Possible Duplicate:
how to convert object into string in php

I have a variable that contain some object (SimpleXML).
Can I change the type of this variable, and to assing it to this variable itself?
Like this:

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

The above code does not work, so the output is still object(SimpleXMLElement) and not a string.

But when I assign it another variable, like $new_test = (string)$test it works well, and the var_dump output is string]

Community
  • 1
  • 1
Shimon S
  • 4,048
  • 2
  • 29
  • 34

5 Answers5

0

If you want the string content, use asXML method.

var_dump($test->asXML());
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

It depends on how SimpleXML implements the magic function __toString(). Its different from class to class. But if its not implemented, PHP will throw a fatal error.

So, typecasting directly from object to string does not work unless the __toString() method is implemented.

mishmash
  • 4,422
  • 3
  • 34
  • 56
  • 1
    When I assign it to another variable [like this `$test2=(string)$test` it works well, and the var_dump output is `sring`] – Shimon S Sep 14 '12 at 07:40
  • I don't know what you are doing, since I don't see your code. But `$var = (string)$var;` is the same as `$var2 = (string)$var;` in the sense that `$var` and `$var2` will both contain the same content. – mishmash Sep 14 '12 at 07:44
  • Thank you very much. you are right, it was another problem in the code. thank you for your help – Shimon S Sep 14 '12 at 08:29
0

You can't convert an object to string just like adding a declaration, it might work but it wont behave like desired there's a greate article though written before here in stack on how you should do it the optimal way which is by adding a tostring method read more here... how to convert object into string in php

Community
  • 1
  • 1
Breezer
  • 10,410
  • 6
  • 29
  • 50
0

Typecast the SimpleXMLObject to a string

$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);
?>

Output

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

http://codepad.org/Bss1rndd

amitchhajer
  • 12,492
  • 6
  • 40
  • 53
0

It depends on the object being converted. For SimpleXML you probably want its asXML method: http://www.php.net/manual/en/simplexmlelement.asxml.php. For general objects, you can typecast to string if the objects implements the __toString() method. Another option would be var_export(...,true), but that is rarely useful except for debugging.

John Dvorak
  • 26,799
  • 13
  • 69
  • 83