I understand how it works but why would we practically use this?
<?php class cat { public function __toString() { return "This is a cat\n"; } } $toby = new cat; print $toby; ?>
Isn't this the same as this:
<?php class cat { public function random_method() { echo "This is a cat\n"; } } $toby = new cat; $toby->random_method(); ?>
can't we just use any other public method to output any text? Why do we need magic method like this one?
The __toString() function returns the string content of an element. This function returns the string content that is directly in the element - not the string content that is inside this element's children!
toString() The toString() method returns a string representing the source code of the specified Function .
Magic methods in PHP are special methods that are aimed to perform certain tasks. These methods are named with double underscore (__) as prefix. All these function names are reserved and can't be used for any purpose other than associated magical functionality. Magical method in a class must be declared public.
__sleep is supposed to return an array of the names of all variables of an object that should be serialized. __wakeup in turn will be executed by unserialize if it is present in class. It's intention is to re-establish resources and other things that are needed to be initialized upon unserialization.
You don't "need" it. But defining it allows your object to be implicitly converted to string, which is convenient.
Having member functions that echo
directly is considered poor form because it gives too much control of the output to the class itself. You want to return strings from member functions, and let the caller decide what to do with them: whether to store them in a variable, or echo
them out, or whatever. Using the magic function means you don't need the explicit function call to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With