oop - Where and why do we use __toString() in PHP? -
i understand how works why practically use this?
<?php class cat { public function __tostring() { return "this cat\n"; } } $toby = new cat; print $toby; ?>
isn't same this:
<?php class cat { public function random_method() { echo "this cat\n"; } } $toby = new cat; $toby->random_method(); ?>
can't use other public method output text? why need magic method one?
you don't "need" it. defining allows object implicitly converted string, convenient.
having member functions echo
directly considered poor form because gives control of output class itself. want return strings member functions, , let caller decide them: whether store them in variable, or echo
them out, or whatever. using magic function means don't need explicit function call this.
Comments
Post a Comment