For this article we’ll be looking at the __toString magic function, and a very handy function it is to. What this function does is allow you to change the default behaviour when outputting an object instance. Consider we had the following class:
PHP Code:
class Member
{
private $m_szEmail;
private $m_szUsername;
public function __construct($szUsername, $szEmail)
{
$this->m_szUsername = $szUsername;
$this->m_szEmail = $szEmail;
}
}
$pMember = new Member('Karl', 'karl@talkphp.com');
echo $pMember;
If we were to run this code, we would see the following output:
Now let’s say throughout our project we will be listing members in the following format:
PHP Code:
Username (Email Address)
Usually, most people would achieve this with code like:
PHP Code:
echo $pMember->getUsername() . " (" . $pMember->getEmail() . ")";
However, what we can do is use the __toString() function to change the default behaviour of the object to string conversion. This would allow us to specify exactly what string is outputted (as we saw previously, by default, the string "Object" is outputted). To make this clearer, let’s add the following method to our class.
PHP Code:
public function __toString()
{
return sprintf('%s (%s)', $this->m_szUsername, $this->m_szEmail);
}
This method should be fairly straight forward, so I won't delve into how the code works, it basically formats and returns our string.
If we were to now execute the script again, this time, we would see the following output:
PHP Code:
Karl (karl@talkphp.com)
We can then easily output a formatted list of members like so:
PHP Code:
foreach ($aMembers as $pMember)
{
echo $pMember . "<br />\n";
}
Which would output something like:
PHP Code:
Karl (karl@talkphp.com)
Wildhoney (wildhoney@talkphp.com)
Bluesage (bluesaga@talkphp.com)
Salathe (salath@talkphp.com)