欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

php 魔术方法__toString()的作用实例,魔术__tostring

来源: javaer 分享于  点击 16812 次 点评:24

php 魔术方法__toString()的作用实例,魔术__tostring


--------PHP魔术方法__toString()----------

当我们调试程序时,需要知道是否得出正确的数据。比如打印一个对象时,看看这个对象都有哪些属性,其值是什么,

如果类定义了toString方法,就能在测试时,echo打印对象体,对象就会自动调用它所属类定义的toString方法,格式化输出这个对象所包含的数据。

这个方法大多数是在写类的时候会使用,为了完善类的健壮性且方便调试使用。


下面我们来看一个__toString()的实例:


class classLeyangjunTest{
	  private $testName = "";
	    function __construct($testName= ""){
	        $this->testName = $testName;
	    }
	    function say(){
	        echo "码农你好,".$this->testName."!";  
	    }
	    function __tostring(){//不加该魔术方法会报错
	        return  "classOver:,".$this->testName."!";    
	    }
	}
	//一:echo strval(new classLeyangjunTest());
	
        //二:$tesObj = new classLeyangjunTest('leyangjun');
	    echo $testObj;

     
//解释
一:不能将 strval() 用于数组或对象,否则会报 :PHP Catchable fatal error:  Object of class classLeyangjunTest could not be converted to string in....错误
二:同样会报错误:PHP Catchable fatal error:  Object of class classLeyangjunTest could not be converted to string in....
意思就是不能将对象转换成string,加上魔术方法__tostring即可输出;



相关文章

    暂无相关文章

用户点评