Home  >  Article  >  Backend Development  >  【php】Using the "__toString()" method

【php】Using the "__toString()" method

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

We have mentioned before that the method of declaring the method name starting with "--" in the class (provided by PHP),

are all methods that are automatically called and executed under different circumstances at a certain time, the "__toString()" method It is also automatically called.

It is automatically called when the object reference is directly output. Earlier we said that the object reference is a pointer.

For example: "$p=new Person()", $p is a Quote,

We cannot use echo to directly output $p, which will output an error like "Catchable fatal error: Object of class Person could not be converted to string",

If you define "__toString()" in the class method, when directly outputting the object reference, no error will be generated,

Instead, the "__toString()" method is automatically called, and the characters returned in the "__toString()" method are output,

So "__toString() "The method must have a return value (return statement).

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

The above introduces the use of [php] "__toString()" method, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn