php 如何在php中将对象转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2469222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert object into string in php
提问by JJ.
Possible Duplicate:
PHP ToString() equivalent
可能的重复:
PHP ToString() 等效
how to convert object into string in php
如何在php中将对象转换为字符串
Actually i am dealing with web service APIs.i want to use output of one API as a input for another API. when i am trying to do this i got error like this:Catchable fatal error: Object of class std could not be converted to string in C:\ ...
实际上我正在处理 Web 服务 API。我想使用一个 API 的输出作为另一个 API 的输入。当我尝试这样做时,我得到了这样的错误:可捕获的致命错误:类 std 的对象无法转换为 C:\ 中的字符串...
this is the output of first API::stdClass Object ( [document_number] => 10ba60 ) now i want only that number to use as input for 2nd AP
这是第一个 API::stdClass 对象( [document_number] => 10ba60 )的输出,现在我只想将该数字用作第二个 AP 的输入
print_r and _string() both are not working in my case
print_r 和 _string() 在我的情况下都不起作用
回答by Greg K
You can tailor how your object is represented as a string by implementing a __toString()method in your class, so that when your object is type cast as a string(explicit type cast $str = (string) $myObject;, or automatic echo $myObject) you can control what is included and the string format.
你可以通过__toString()在你的类中实现一个方法来定制你的对象如何表示为字符串,这样当你的对象被类型转换为字符串(显式类型转换$str = (string) $myObject;或自动echo $myObject)时,你可以控制包含的内容和字符串格式。
If you only want to display your object's data, the method above would work. If you want to store your object in a session or database, you need to serializeit, so PHP knows how to reconstruct your instance.
如果您只想显示对象的数据,上面的方法会起作用。如果要将对象存储在会话或数据库中,则需要对其进行序列化,因此 PHP 知道如何重建您的实例。
Some code to demonstrate the difference:
一些代码来演示差异:
class MyObject {
protected $name = 'JJ';
public function __toString() {
return "My name is: {$this->name}\n";
}
}
$obj = new MyObject;
echo $obj;
echo serialize($obj);
Output:
输出:
My name is: JJ
O:8:"MyObject":1:{s:7:"*name";s:2:"JJ";}
我的名字是:JJ
O:8:"MyObject":1:{s:7:"*name";s:2:"JJ";}
回答by Webleeuw
Use the casting operator (string)$yourObject;
使用转换运算符 (string)$yourObject;
回答by Wolph
There is an object serializationmodule, with the serializefunction you can serialize any object.
回答by Tomasz Struczyński
In your case, you should simply use
在你的情况下,你应该简单地使用
$firstapiOutput->document_number
as the input for the second api.
作为第二个 api 的输入。

