【问题标题】:How to I return different type with __toString() method?如何使用 __toString() 方法返回不同的类型?
【发布时间】:2011-04-06 06:45:17
【问题描述】:

我们使用 __toString() 来返回类的默认值:

<?php

class my
{
   public function __toString()
   {
      return "asdasd";
   }
}

?>

它只返回字符串类型。但我想返回资源类型:

<?php

class my
{
   public function __toString()
   {
      return imagecreatefromjpeg("image.jpg");
   }
}

?>

它不起作用。怎么做?有什么方法可以代替 __toString() 或任何使用 __toString 的方法吗?

【问题讨论】:

标签: php return tostring


【解决方案1】:

建议您编写自己的方法__toResource() 或类似方法。尝试使用 __toString() 执行此操作是错误的,因为您没有返回字符串 - 您可能会在一年左右的时间里混淆未来的开发人员甚至您自己。

编辑

回复你的评论,像这样?

// Use one _ as suggested by Artefacto
public function _toResource()
{
    // Return the resource object
    return imagecreatefromjpeg("image.jpg");
}

public function __toString()
{
   // Return the filename as a string
   return "image.jpg";
}

【讨论】:

  • 不要在方法名称前加上__。这些是保留的,将来可能会使用。
  • 对不起。有没有什么神奇的函数叫__toResource,还是我没听懂?
  • @sundowatch,不,没有。写你自己的。 @Artefacto,好点。使用 _ 而不是 __。我会相应地编辑我的帖子。
  • @sundowatch:如果我理解正确的话,你想要imagesx( $yourObject ); 这样的东西。那根本行不通。没有接口,没有用于转换 object=>resource 的“魔术”方法。所有那些期望资源作为参数的内置或扩展模块函数(到目前为止我已经看到)通过 zend_parse_arg_impl() 解析参数,并且对于该函数的资源,该函数仅测试参数 is 是否为资源,没有转化。
【解决方案2】:

这是不可能的。顾名思义,__toString 应该返回一个字符串。

甚至不允许转换为字符串的东西:

class my
{
   public function __toString()
   {
      return 6;
   }
}

//Catchable fatal error: Method my::__toString() must return a string value    
echo(new my());

如果您尝试在执行时恢复图像的内容,例如echo(new my),你可以这样做:

class my
{
   public function __toString()
   {
      return (string) file_get_contents("myimage.jpeg");
   }
}

【讨论】:

  • 你是对的。但我会返回图像资源,然后我会像这样处理这个图像: $img = new my(); imagecopymergegray($dst,$img,0,0,0,0,0); imagejpeg($dst,"image2.jpg");我做不到。
  • 我不想归档内容。我要图片资源类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
相关资源
最近更新 更多