當echo一個對象的時候,會報錯誤 Object of class Person could not be converted to string 我們可以通過魔術方法__tostring() 把對象轉成字元串 繼續改造php靜態變數與方法與phar的使用 ghostconfig.php ghost ...
當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(); ?>
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可以使用匿名類簡化