views:

100

answers:

2

We use __toString() to returning class's default value like that:

<?php

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

?>

It returns only string type. But I want to return resource type:

<?php

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

?>

It doesn't work.How to do it?Is there any method instead of __toString() or any way with using __toString?

+9  A: 

Suggest you write your own method __toResource() or similar. Trying to do this using __toString() would be wrong, as your not returning a String - you might confuse future developers or even yourself a year or so down the line.

Edit

In answer to your comment, like this?

// 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";
}
jakenoble
So, how will do it?
sundowatch
@sundowatch see my edit
jakenoble
Don't prefix method names with `__`. These are reserved and may be used in the future.
Artefacto
I am sorry. Is there any magic function called __toResource, or didn't I understand you well?
sundowatch
@sundowatch, no there isn't. Write your own. @Artefacto, good point. Use _ not __. I'll edit my post accordingly.
jakenoble
@sundowatch: If I understand you correctly you want something like `imagesx( $yourObject );`. That simply won't work. There's no interface, no "magic" method that is used to cast object=>resource. All those built-in or extension module functions (I've seen so far) that expect a resource as parameter parse parameters via zend_parse_arg_impl() and for resources that function simply tests if the parameter _is_ a resource, no conversion.
VolkerK
+1  A: 

It's not possible. As the name says, __toString should return a string.

Not even something that is convertible to a string is allowed:

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

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

If you are trying to have the contents of the image back when do do e.g. echo(new my), you can do:

class my
{
   public function __toString()
   {
      return (string) file_get_contents("myimage.jpeg");
   }
}
Artefacto
You are right. But I will return image resource and than I will process this image like that:$img = new my();imagecopymergegray($dst,$img,0,0,0,0,0);imagejpeg($dst,"image2.jpg");I can't do it.
sundowatch
I don't want to file content. I want to image resource type.
sundowatch