Wednesday, February 19, 2014

Programmer's Diary: Transforming PHP Objects to Strings

In my upcoming programming course for +Nettuts+  I will implement a persistence layer for the application developed throughout the course. For the sake of simplicity I decided to make it a file persistence and keep information in plain text. This was a good occasion to use a nice PHP trick to convert simple objects into plain text.

Our objects are books and besides the fact that there is an abstract book class there are a lot of specific implementations for different kind of books, like novels. Each is a little different than the other, so saving all the books in the same text format would have been impossible.

PHP offers a magic method called __toString(). Creating an implementation for this method, on any object, will allow you to use that object in a string context. Let's see a basic example.

class SystemInformation {

 private $cpu;
 private $ram;

 function __construct($cpu, $ram) {
  $this->cpu = $cpu;
  $this->ram = $ram;

 function __toString() {
  return "CPU: " . $this->cpu . "%" .
        "\nMemory: " . $this->ram . "MB";

If we create such an object and try to run it in a string context, like in echo(), it will be automatically converted to string, using whatever we return in __toString().

$sysInfo = new SystemInformation(40,1024);
echo $sysInfo;

This will output:

CPU: 40%
Memory: 1024MB

You can also use it in some other contexts also, for example this test will pass just fine:

$this->assertTrue(strpos($sysInfo, 'CPU') !== false);

And when PHP is not smart enough to figure out that you want the object as string, you can always call __toString() on it directly.

$this->assertRegExp('/CPU/', $sysInfo->__toString());

For the complete example with the whole application I mentioned at the beginning, keep an eye on the +Nettuts+ premium courses. Have a nice day of programming.