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

Reflections is slow, and I think it's the worst solution to use them.

bool method_exists ( mixed $object , string $method_name )

object - An object instance or a class name (http://php.net/manual/en/function.method-exists.php)

There is no need to create an object to checking for existence of a method.

method_exists('foo', '__toString')

or

interface StringInterface{
   public function __toString() :string;
}


class Foo implement StringInterface {...}

->>(new MyClass) instanceof StringInterface

I must be doing something wrong somewhere else, because this works:

class Test {

function __toString() {
    return 'Test';
}

}

$test = new Test();

echo method_exists($test, '__toString');

You should be able to use reflection: http://www.php.net/manual/en/reflectionclass.hasmethod.php


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

Tags:

Php

String

Object