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

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

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



        
10条回答
  •  离开以前
    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
    

提交回复
热议问题