Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where and why do we use __toString() in PHP?

Tags:

oop

php

tostring

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?

like image 895
Stann Avatar asked Mar 02 '11 19:03

Stann


People also ask

What is __ toString in PHP?

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!

What is the function of toString ()?

toString() The toString() method returns a string representing the source code of the specified Function .

Why we use magic methods in PHP?

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.

What's the difference between __ sleep and __ wakeup?

__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.


1 Answers

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.

like image 99
Lightness Races in Orbit Avatar answered Sep 21 '22 12:09

Lightness Races in Orbit