When using this function:
http://getkirby.com/docs/cheatsheet/helpers/thumb
How can this:
echo thumb()
…give different result than this:
print_r(thumb()
For readability I did not add the arguments. The real thumb() function looks like this:
thumb( $page->image(), array('width' => 300) )
Question
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: http://php.net/manual/en/language.oop5.magic.php#object.tostring
1 Like