分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

php魔术方法__tostring的应用

发布时间:2023-09-06 01:51责任编辑:胡小海关键词:暂无标签

当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的应用

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved