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!

4 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

Anil Gupta said...

The blog is absolutely truly incredible. Lots of large information and inspiration, both of which we all need.
Web Designing Company in Bangalore, Web Development Company Bangalore

Prasanth said...

Good work…unique site and interesting too… keep it up…looking forward for more updates.and Helped us to convince most on how this process works and what they could achieve by following these guidelines.
UI Design Company Bangalore, Web Application Development Services in Bangalore