How can "echo thumb()" give different result than "print_r(thumb())"?

When using this function:

How can this:

echo thumb()

…give different result than this:


For readability I did not add the arguments. The real thumb() function looks like this:

thumb( $page->image(), array('width' => 300) )


How is it possible to return a string on echo and an object on print_r?

Also on stackoverflow:

but they don’t seem to like my question at all, or the do not understand it.

I think the answer is in this bit of code (at the end, __toString() function):

   * Generates and returns the full html tag for the thumbnail
   * @param array $attr An optional array of attributes, which should be added to the image tag
   * @return string
  public function tag($attr = array()) {

    // don't return the tag if the url is not available
    if(!$this->result->url()) return false;

    return html::img($this->result->url(), array_merge(array(
      'alt'    => isset($this->options['alt'])   ? $this->options['alt']   : $this->result->name(),
      'class'  => isset($this->options['class']) ? $this->options['class'] : null,
    ), $attr));


   * Makes it possible to echo the entire object
  public function __toString() {
    return $this->tag();

1 Like

It’s some PHP magic happening there.

Classes have the option the implement the __toString() method which will be used automatically, whenever an object get’s used as a string (just like when you try to use echo on it).

print_r() however, will output an object with all its properties visible; it will create a visual, textual representation of the object for debugging purposes.

You can read more details about PHPs magic methods in the documentation:

1 Like