Application of Php Magic method __tostring

Source: Internet
Author: User
Tags stdin

When an object is echo, an error is reported

Object of class person could not being converted to string

We can turn the object into a string by magic method __tostring ()

 #  !/usr/bin/php  <?php  class   person{ 
   
    public  
     $name  = ' GHOSTWU ' 
     public   $age  = 20;  function   __tostring () {return  Json_encode ( $this   );  }}  echo  new   person (); ? 
   

Continue to transform PHP static variables and methods and the use of Phar

ghostconfig.php

<? PHP     class ghostconfig{            public$projName = ';              Public $author = ";             function __tostring () {                    return$this  );    }? >

ghostinit.php

require("ghostconfig.php" ); classghostinit{Static $v= ' Ghost version is 1.1 '; Static functioninit () {$config=NewGhostconfig (); Echo"Pls input project name?".Php_eol; $config->projname =fgets(STDIN); Echo"Pls input author?".Php_eol; $config->author =fgets(STDIN); Echo"The project information you entered is as follows:".Php_eol; Echo $config; }        Static functionGetConfig ($conf ){            $STD=NewStdClass (); foreach($conf  as $k=$v ){                $STD-$k=$v; }            return $STD; }        function__tostring () {returnJson_encode ($this ); }        Static functionMake () {$pchar=NewPhar ("Ghost.phar"); $pchar->buildfromdirectory (dirname(__file__)); $pchar->setstub ($pchar->createdefaultstub (' Ghost ')); $pchar->compressfiles (Phar::GZ); }        Static function__callstatic ($m,$args ){            Echo' Error function '; }    }

PHP7 can use anonymous classes to simplify

Application of Php Magic method __tostring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.