dongni9825 2015-04-19 11:20
浏览 179
已采纳

PHP echo类对象属性

Is it possible to echo class object so it will show some property of this object?

Let's say we've got such class

class Color {

    public $color = "";

    function __construct($color) {
        $this->color = $color;
    }

}

and then we create it's instance and echo it:

$myColor = new Color("red");
echo $myColor; //I want it to echo 'red' ( same as I'd do echo $myColor->color )

What happens here is my object has prop color. And when I have echo $object I want it to really do echo $object->prop

Is it possible to make such 'echoing' handler?

  • 写回答

1条回答 默认 最新

  • duanqu9292 2015-04-19 11:22
    关注

    Implement the magic __toString method:

    class Color {
    
        public $color = "";
    
        function __construct($color) {
            $this->color = $color;
        }
    
        public function __toString() {
          return $this->color;
        }
    
    }
    

    This method will be automatically called by PHP if an instance is forced to be converted to a string, e.g. when echoing it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多台相同IP产品如何组网
  • ¥30 关于php页面调取、更新数据提交刷新等问题
  • ¥50 使用 java+selenium 接管手动打开的IE浏览器
  • ¥15 ios 新安装app收不到fcm推送
  • ¥15 有没有实力的写手?有过成品的优先
  • ¥15 图像信息库的建立与识别
  • ¥15 韩国网站购物,KG支付的支付回调如何解决
  • ¥15 workstation导入ovf文件,报错,怎么解决呢?
  • ¥15 关于#c语言#的问题:构成555单稳态触发器,采用LED指示灯延时时间,对延时时间进行测量并显示(如楼道声控延时灯)需要Proteus仿真图和C语言代码
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,怎样解决呢?