如何在php中将对象转换为字符串 [英] how to convert object into string in php

查看:107
本文介绍了如何在php中将对象转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
等同于PHP ToString()

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

实际上,我正在处理Web服务API.我想使用一个API的输出作为另一个API的输入.当我尝试执行此操作时,出现如下错误:可捕获的致命错误:类std的对象无法在C:\ ...中转换为字符串.

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

print_r和_string()都无法正常工作

解决方案

您可以通过在类中实现__toString()方法来定制对象如何以字符串形式表示,这样当对象为序列化它,因此PHP知道如何重建您的实例.

一些代码可以证明两者之间的区别:

class MyObject {

  protected $name = 'JJ';

  public function __toString() {
    return "My name is: {$this->name}\n";
  }

}

$obj = new MyObject;

echo $obj;
echo serialize($obj);

输出:

我的名字是:JJ

O:8:"MyObject":1:{s:7:"* name"; s:2:"JJ";}

Possible Duplicate:
PHP ToString() equivalent

how to convert object into string in 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:\ ...

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

print_r and _string() both are not working in my case

解决方案

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

这篇关于如何在php中将对象转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆