Jump to content

__toString()


The Little Guy

Recommended Posts

no, this isn't for debugging.

 

I have two methods that return objects, and if you echo them out I want to know which on did so my __toString knows what to do. I am going to add more, that when echoed out use __toString, but they will return something completely different.

 

The two current ones that use __toStirng return the same thing, which is a modified version of a GET query string (adding/removing key/value combinations).

So what I have done, is set a private property called $function_name, and when ever a funciton name gets called (other than magic methods) it updates that property. So when __toString gets called I know what the last method that ran was.

 

Here is a simplified example:

<?php
class MyClass{
private $function_name = null;
private $hello = 'hello';
private $goodbye = 'goodbye';
public function __toString(){
	switch($this->function_name){
		case 'hello':
			return $this->hello;
		case 'goodbye':
			return $this->goodbye;
	}
}
public function hello(){
	$this->function_name = __FUNCTION__;
	return $this;
}
public function goodbye(){
	$this->function_name = __FUNCTION__;
	return $this;
}
}

$mc = new MyClass();
echo $mc->hello();			// prints hello
echo $mc->goodbye();			// prints goodbye
echo $mc=>hello()->goodbye();		// prints goodbye
echo $mc=>hello()->goodbye()->hello();	// prints hello
?>

Link to comment
https://forums.phpfreaks.com/topic/243207-__tostring/#findComment-1249568
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.