如何用__toString()方法返回不同的类型?

sun*_*tch -3 php return tostring

我们使用__toString()来返回类的默认值,如下所示:

<?php

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

?>
Run Code Online (Sandbox Code Playgroud)

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

<?php

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

?>
Run Code Online (Sandbox Code Playgroud)

它不起作用.怎么做?是否有任何方法而不是__toString()或任何方式使用__toString?

Jak*_*e N 12

建议你编写自己的方法__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";
}
Run Code Online (Sandbox Code Playgroud)

  • 不要使用`__`作为方法名称的前缀.这些是保留的,可能在将来使用. (4认同)