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

后端 未结 10 1653
星月不相逢
星月不相逢 2021-01-01 10:34

I understand how it works but why would we practically use this?



        
相关标签:
10条回答
  • 2021-01-01 11:03

    __toString() is called when an object is passed to a function (esp echo() or print()) when its context is expected to be a string. Since an object is not a string, the __toString() handles the transformation of the object into some string representation.

    0 讨论(0)
  • 2021-01-01 11:05

    __String helps us it returning error message in case there is some error in constructor.

    Following dummy code will clarify it better. Here if creation of object is failed, an error string is sent:

    class Human{
       private $fatherHuman;
       private $errorMessage ="";
       function __construct($father){
             $errorMessage = $this->fatherHuman($father);
       }
    
       function fatherHuman($father){
            if($father qualified to be father){
                $fatherHuman = $father;
                return "Object Created";//You can have more detailed string info on the created object like "This guy is son of $fatherHuman->name"
             } else {
                return "DNA failed to match :P";
             }
        }
    }
    
    function run(){
       if(ctype_alpha($Rahul = Human(KingKong)){
            echo $Rahul;
       }
    
    }
    
    run();   // displays DNA failed to match :P
    
    0 讨论(0)
  • 2021-01-01 11:05

    Using __toString() overrides the operator that is called when you print objects of that class, so it makes it easier for you to configure how an object of that class should be displayed.

    0 讨论(0)
  • 2021-01-01 11:11

    it's like override with c# :

    class Person
    
    {
    
    public Person(string firstName, string lastName)
    
    {
    
    FirstName = firstName;
    
    LastName = lastName;
    
    }
    
    public string FirstName { get; set; }
    
    public string LastName { get; set; }
    
    public override string ToString()
    
    {
    
    return FirstName + “ “ + LastName;
    
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题