【问题标题】:how can I make an object from string contains printed object如何使字符串中的对象包含打印对象
【发布时间】:2013-04-09 02:49:08
【问题描述】:

我有一些代码:

测试控制器:

        Class test extends CI_Controller{
            public function print_object(){
                 $x = (object) array('a'=>'A', 'b'=>'B', 'C');
                 echo '<pre>'.print_r($x, true).'</pre>';
            }
        }

Test2 控制器:

        Class test2 extends CI_Controller{
            public function get_printed_object(){
                 $url = "http://localhost/project/test/print_object";
                 (object) $str = file_get_contents($url);
                 echo $str->a; //won't make it. resulting error
            }
        }

线

echo $str->a;

导致警告:尝试获取非对象的属性

我可以重新制作打印到字符串的 $x 对象吗?

【问题讨论】:

    标签: php string codeigniter object


    【解决方案1】:

    您遇到的主要问题是 file_get_contents 返回带有 url 输出的字符串。 $str 因此只是一个字符串,即使是演员也不会改变它。

    如果要将其转换为对象,则可以json_encode(或序列化)并在测试中输出。然后 test2 必须 json_decode($str) 重新创建对象。

    【讨论】:

      【解决方案2】:

      您应该使用原生的serialize()unserialize() 函数。 通过序列化一个对象,您将获得一个包含所有信息的类 json(它不是 json,但看起来像)字符串。反序列化时,您会获得序列化对象的克隆,并且可以正常访问其方法和属性。

      查看这个函数的 php 手册:

      http://php.net/manual/en/function.unserialize.php

      http://php.net/manual/en/function.serialize.php

      最后一页是一个很酷的例子:

      http://php.net/manual/en/language.oop5.serialization.php

      【讨论】:

        猜你喜欢
        • 2023-03-11
        • 2020-10-18
        • 2021-12-13
        • 1970-01-01
        • 1970-01-01
        • 2018-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多