Heim  >  Artikel  >  Backend-Entwicklung  >  【php】“__toString()”方法使用

【php】“__toString()”方法使用

WBOY
WBOYOriginal
2016-08-08 09:24:421243Durchsuche

我们前面说过在类里面声明“--”开始的方法名的方法(PHP给我们提供的),

都是在某一时刻不同情况下自动调用执行的方法,“__toString()”方法也是一样自动被调用的,

是在直接输出对象引用时自动调用的, 前面我们讲过对象引用是一个指针,

比如说:“$p=new Person()“中,$p就是一个引用,

我们不能使用echo 直接输出$p, 这样会输出”Catchable fatal error: Object of class Person could not be converted to string“这样的错误,

如果你在类里面定义了“__toString()”方法,在直接输出对象引用的时候,就不会产生错误,

而是自动调用了”__toString()”方法, 输出“__toString()”方法中返回的字符,

所以“__toString()”方法一定要有个返回值(return 语句).

	function __toString(){
			/* 加到session中, 存储下标为code */
			$_SESSION["code"] = strtoupper($this->checkCode);  //随机产生的字符内容存在session里面
			$this->outImg();             					
			return '';
		}

以上就介绍了【php】“__toString()”方法使用,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn