/**
* Return the role string in attempts to use the object as a string.
*
* @since 2.0.0
* @access public
* @return string
*/
public function __toString() {
return $this->name;
}
what kind of function is this? No arguments and nothing else. How is this returning name?
It’s returning the name property on the object itself.
It probably looks a bit like this:
class Foo
{
private $name; // private propery "name" - the class itself may access it - nobody else is allowed to touch it
public function __construct($name)
{
$this->name = $name; // set private property "name" to value $name
}
public function __toString()
{
return $this->name; // return value from private property "name"
}
}
(omitted types for sake of simplicity. Everywhere a type could be used assume string)
Well you could use this for example for logging purposes. Suppose you have a User class with a __toString() that returns the username, you could log it like so:
which will resolve to User rpkamp logged in for example.
If then later you decide you want to log more information about users (like their level) you can add that to the __toString and it could for example become User rpkamp (Advisor) logged in.
Then it is changed everywhere the user is logged, without having to change a single line of logging code.
It is most effective when used with value/entity objects.
Below is a very simplified example:
final class Money {
private $amount;
public function __construct($amount) {
$this->amount = $amount;
}
public function __toString()
{
return '$'.number_format($this->amount, 2);
}
}
$amount = new Money(100);
echo 'I just spent ',$amount;
// I just spent $100.00
As you can see, by using the ability to decide how the class behaves when it interacts with a string (consider it as the object is “being cast” to string).
In the example, in the base code you had a value object for money that contained the value of 100. Then with __toString we placed the currency indicator in front and also made sure it had two decimal places, making it very easy to use when displaying the information to the front end. Any place you want to use a money amount, you just echo/print etc. the money value object directly and you do not need to worry about the correct formatting or currency, as the value object handle that.
I see many programmers making the mistake and that is a good reason to explain the mistake. I totally understand that you were just following the lead of many others.