Monday, November 2, 2009

Getting value from an object (or instance of a class) in PHP 5

Just earlier on I was working on the String class in the Samstyle PHP Framework. I was glad that I read the PHP manual and found this magical method in PHP5 OOP called __toString().

Using __toString(), you can actually return a value for the object/instance of a class.

See the example below:

class MyClass{

  function __construct(){
    // constructor
  }

  function __toString(){
    // to String
    return 5;
  }

}

$inst = new MyClass();

echo $inst; // echos 5

How powerful!

2 programmer comments:

chris said...

Wow man! Cool stuff! Ever tried running your stuff on Windows? Do some benchmarking?

- Chris
(chism@microsoft.com)

thephpdeveloper said...

Hi Chris

Yeah I running Windows, but using Apache instead of IIS because I had to emulate linux server which are used for production.

Yeah I ran PHP on IIS before by adding the PHP dll as filter to run all *.php files.

Cheers
Sam