Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

object

php

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

method_exists($object, '__toString');
like image 705
Kirk Ouimet Avatar asked May 07 '11 00:05

Kirk Ouimet


4 Answers

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

like image 187
tereško Avatar answered Nov 19 '22 00:11

tereško


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
like image 27
omnomnom Avatar answered Nov 19 '22 01:11

omnomnom


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

class Test {

function __toString() {
    return 'Test';
}

}

$test = new Test();

echo method_exists($test, '__toString');
like image 4
Kirk Ouimet Avatar answered Nov 19 '22 02:11

Kirk Ouimet


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

like image 3
linuts Avatar answered Nov 19 '22 02:11

linuts