What that code is doing, is looking at the
output buffer while generating the string that the class should return.
_toString is what's called a "magic method" in PHP classes. Basically, any time an instance of a class, for instance when it's passed to echo, needs to return a string for whatever reason, _toString is a method you can define in the class definition as a way to determine how your class will return a string.
For instance, if you have a class named "person" with two attributres, "first_name" and "last_name".
class
{
public $first_name, $last_name;
public function __construct($first, $last)
{
$this->first_name = $first;
$this->last_name = $last;
}
}
- class
- {
- public $first_name, $last_name;
- public function __construct($first, $last)
- {
- $this->first_name = $first;
- $this->last_name = $last;
- }
- }
You could setup something like this to get a "person"'s full name.
$me = new person('joe', 'bert');
echo $me->first_name . ' ' . $me->last_name;
- $me = new person('joe', 'bert');
- echo $me->first_name . ' ' . $me->last_name;
Or, you could setup a _toString method, which PHP will know to call automatically in order to generate the string when you do something such as
echo new person('joe', 'bert');
For instance
class
{
public $first_name, $last_name;
public function __construct($first, $last)
{
$this->first_name = $first;
$this->last_name = $last;
}
public function __toString()
{
return $this->first_name . ' ' . $this->last_name;
}
}
$me = new person('joe', 'bert');
define('GREETING', 'Hello, my name is %s');
printf(GREETING, $me);
- class
- {
- public $first_name, $last_name;
- public function __construct($first, $last)
- {
- $this->first_name = $first;
- $this->last_name = $last;
- }
- public function __toString()
- {
- return $this->first_name . ' ' . $this->last_name;
- }
- }
- $me = new person('joe', 'bert');
- define('GREETING', 'Hello, my name is %s');
- printf(GREETING, $me);
Now realistically, chances are you're never going to have a class that looks at the output buffer before generating a string for output. The only time I could think it would even be reasonable (somewhat) is if you had a class that defined a part of the English language that looked at the previously printed output to see how it should print something.
For instance, if you had a keyword that could be singular or plural depending on what was printed before it, you could return whichever one would make more sense for the currently generated sentence. Now, in 7 years I've never seen anything like that done, the example I posted is actually the first time I've seen anything like this period. So, you're probably safe assuming it's almost never going to be something you need to worry about,

Strong with this one, the sudo is.