码迷,mamicode.com
首页 > Web开发 > 详细

php魔术方法__tostring的应用

时间:2018-04-27 23:50:11      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:str   getconf   could not   ref   nbsp   pos   created   public   each   

当echo一个对象的时候,会报错误

Object of class Person could not be converted to string

我们可以通过魔术方法__tostring()  把对象转成字符串

#!/usr/bin/php
<?php
    
    class Person{
            public $name = ‘ghostwu‘;
            public $age = 20;

            function __toString(){
                    return json_encode( $this );
            }
    }
    
    echo new Person();
?>

 继续改造php静态变量与方法与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 "您输入的项目信息如下:" . 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可以使用匿名类简化

 

php魔术方法__tostring的应用

标签:str   getconf   could not   ref   nbsp   pos   created   public   each   

原文地址:https://www.cnblogs.com/ghostwu/p/8964682.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!