The application of php magic method __tostring php static variables and methods and the use of phar

When echoing an object, an error will be reported

Object of class Person could not be converted to string

We can convert the object to a string through the 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 the use of php static variables and methods and phar

ghostconfig.php

<?php
    class ghostconfig{
            public $projName = '';
            public $author = '';

            function __tostring(){
                    return json_encode( $this );
            }
    }

?>

ghostinit.php

require( "ghostconfig.php" );
    class ghostinit{
        static $v = 'ghost version is 1.1';

        static function init(){
            $config = new ghostconfig();
            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 function getConfig( $conf ){
            $std = new stdClass();
            foreach( $conf as $k => $v ){
                $std->$k = $v;
            }
            return $std;
        }

        function __tostring(){
            return json_encode( $this );
        }

        static function make(){
            $pchar=new Phar("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 be simplified using anonymous classes

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324979008&siteId=291194637
Recommended