如何在PHP中查看对象是否实现 - > __ toString()?

Kir*_*met 17 php string object

反正是否有对象专门实现 - > __ toString?这似乎不起作用:

method_exists($object, '__toString');
Run Code Online (Sandbox Code Playgroud)

ter*_*ško 11

有两种方法可以检查它.

让我们假设您有课程:

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

class Bar
{
}
Run Code Online (Sandbox Code Playgroud)

然后你可以做到:

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

$rc = new ReflectionClass('Bar');       
var_dump($rc->hasMethod('__toString'));
Run Code Online (Sandbox Code Playgroud)

或使用:

$fo = new Foo;
var_dump( method_exists($fo , '__toString'));
$ba = new Bar;
var_dump( method_exists($ba , '__toString'));
Run Code Online (Sandbox Code Playgroud)

区别在于,在第一种情况下,该类实际上并未实例化.
您可以在这里查看演示:http://codepad.viper-7.com/B0EjOK


Kir*_*met 5

您一定在其他地方做错了什么,因为这是有效的:

class Test {

function __toString() {
    return 'Test';
}

}

$test = new Test();

echo method_exists($test, '__toString');
Run Code Online (Sandbox Code Playgroud)


小智 5

反射很慢,我认为使用它们是最糟糕的解决方案。

bool method_exists ( mixed $object , string $method_name )
Run Code Online (Sandbox Code Playgroud)

object - 对象实例或类名(http://php.net/manual/en/function.method-exists.php

无需创建对象来检查方法是否存在。

method_exists('foo', '__toString')
Run Code Online (Sandbox Code Playgroud)

或者

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


class Foo implement StringInterface {...}

->>(new MyClass) instanceof StringInterface
Run Code Online (Sandbox Code Playgroud)