【问题标题】:php Object to Stringphp 对象转字符串
【发布时间】:2009-09-16 16:24:22
【问题描述】:

我正在尝试自学php...所以请善待我。

我正在尝试关注this tutorial 如何缓存文件...我要缓存的页面仅为 HTML,因此我已修改 php 以仅处理数据。我知道缓存部分正在工作,当我尝试修改结果时,我在下面的 str_replace 行中收到“可捕获的致命错误:类缓存的对象无法转换为字符串”。

我尝试过使用__toString method here,也尝试过使用serialize。我有什么遗漏吗?

编辑:哦,我什至尝试过casting operators

 $caching = new Caching( "my.htm", "http://www.page-I-want.com/" );
 $info = new TestClass($caching);
 $info = str_replace( "<img src='/images/up.jpg'>","<div class='up'></div>", $info );

我的 var_dump($caching);如下:

object(Caching)#1 (2) { ["filePath"]=>  string(9) "cache.htm" ["apiURI"]=>  string(27) "http://www.page-I-want.com/" } 

好的,我现在看到问题在于caching.php 没有将值返回给$caching 字符串。任何人都可以查看下面的链接并帮助我弄清楚为什么它不起作用?谢谢!

我刚刚发布了我的整个caching.php 文件here

【问题讨论】:

  • 您是否尝试在对象被序列化时替换图像,然后反序列化它?
  • 那么你确实在你的缓存类中实现了 __toString 方法吗?它是什么样子的? (先调用serialize时不需要,但最好不要改变序列化对象的内容)
  • 如果你能添加什么 var_dump($caching); 帮助你会更容易打印。
  • 我把 serialize 函数留在那里以显示我添加它的位置...我现在看到我不应该使用 serialize - 我编辑了帖子以显示我是如何使用 TestClass 从我提到的链接
  • @Raynet:添加了上面的 var_dump - 嗯,这是否意味着我的缓存类没有返回值?

标签: php caching tostring


【解决方案1】:

您链接的网站上的代码通过从您提供的 URL 下载页面并为艺术家解析它,然后将它们保存到缓存文件来工作。缓存对象只包含两个变量;文件路径和 apiURI。如果您想修改页面解析和转换为缓存的 XML 文件的方式,您应该更改 stripAndSaveFile 函数。

这里是一个如何修改 Caching.php 来做你想做的事的例子:

  function stripAndSaveFile($html) {
        //mange the html code in any way you want
        $modified_html = str_replace( "<img src='/images/up.jpg'>","<div class='up'></div>", $html );
        //save the xml in the cache
        file_put_contents($this->filePath, $modified_html);  
  }         

编辑:

其他选项是扩展缓存类,在你的 php 代码中使用你可以做的类:

  class SpecialCaching extends Caching {
        var $html = "";
        function stripAndSaveFile($html) {
              //mange the html code in any way you want
              $this->html = $html;
        }
  }

  $caching = new SpecialCaching( "my.htm", "http://www.page-I-want.com/" );
  $info = $caching->html;
  $info = str_replace( "<img src='/images/up.jpg'>","<div class='up'></div>", $info );

【讨论】:

  • 我重命名了stripAndSaveFile函数,我不想修改cache.php文件中的数据,因为我会将它用于其他文件并替换不同的对象——我将函数添加到顶部发布。
  • 我放弃并替换了 Caching.php 文件中的字符串,现在它可以工作了...感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2014-04-09
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多