如何在 php 中将对象转换为字符串

可能的复制品:
PHP ToString ()等价于

如何在 php 中将对象转换为字符串

实际上我正在处理 Web 服务的 API。我想使用一个 API 的输出作为另一个 API 的输入。当我尝试这样做时,我得到了这样的错误: Catchable 致命错误: 类 std 的对象不能被转换为字符串在 C: ..。

这是第一个 API: : stdClass 对象([ document _ number ] = > 10ba60)的输出,现在我只希望将这个数字用作第二个 AP 的输入

Print _ r 和 _ string ()在我的例子中都不起作用

367743 次浏览

You have the print_r function, check docs.

There is an object serialization module, with the serialize function you can serialize any object.

Use the casting operator (string)$yourObject;

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.

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 serialize it, so PHP knows how to reconstruct your instance.

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";}

In your case, you should simply use

$firstapiOutput->document_number

as the input for the second api.