PHP面向对象魔术方法之__toString函数

基本介绍:

当我们希望将一个对象当做字符串来输出时,就会触发__toString魔术方法.

 

<?php
    header('content-type:text/html;charset=utf-8');

    //__toString函数
    class Sheep{
        
        public $name;
        protected $food;

        public function __construct($name, $food){
            $this->name = $name;
            $this->food = $food;
        }
        //魔术方法
        //当输出一个对象时,就会触发该函数
        //1. _toString 没有形参
        //2. _toString 要求返回一个字符串
        //3. 当我们在项目开发时,需要 debug(找bug), 可以通过他输出对象信息  
        public function __toString(){
            
            return '名字: ' . $this->name . ' 食物是 ' . $this->food;
        }
    }

    $sheep = new Sheep('懒洋洋', '狼');

    //当我们将一个对象直接输出时,就会触发魔术方法__toString,
    //如果你没有写,就会报错
    echo $sheep;

 

 

 

转载于:https://www.cnblogs.com/lsqbk/p/10389372.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值