phpstringobject

How do I check to see if an object implements ->__toString() in PHP?


Is there anyway to see if an object specifically implements ->__toString? This doesn't seem to work:

method_exists($object, '__toString');

Solution

  • There are two way to check it.

    Lets assume you have classes:

    class Foo
    {
        public function __toString()
        {
            return 'foobar';
        }
    }
    
    class Bar
    {
    }
    

    Then you can do either:

    $rc = new ReflectionClass('Foo');       
    var_dump($rc->hasMethod('__toString'));
    
    $rc = new ReflectionClass('Bar');       
    var_dump($rc->hasMethod('__toString'));
    

    or use:

    $fo = new Foo;
    var_dump( method_exists($fo , '__toString'));
    $ba = new Bar;
    var_dump( method_exists($ba , '__toString'));
    

    Difference is that in first case the class is not actually instantiated.
    You can look at demo here : http://codepad.viper-7.com/B0EjOK