What is the right way to use "instanceof"?


What is the right way to use "instanceof"?

我有这个代码:

$i = 0;
foreach ($entities as $entity)
{
    $person = $entity->getPerson();
    echo "Iteration: " . $i . " Person Type: " . get_class($person);
    if ($person instanceof NaturalPerson)
    {
        $id = $person->getIdentificationType() . $person->getCI();
    }
    else
    {
        $id = $person->getIdentificationType() . $person->getRIF();
    }
    $i++;
    $order['id'] = $id;
    $orders[] = $order;
}

但每当我运行该函数时,我都会出现以下错误:

尝试在类上调用方法"getRIF"中的"Tanane''FrontendBundle''Entity''NaturalPerson"/var/www/html/tanane/src/tanane/BackendBundle/Controller/OrderController.php第114行。你是说要调用:"getCI"、"getId"吗?

我不知道为什么第一行的echo返回这个:

Iteration: 0 Person Type: Tanane'FrontendBundle'Entity'LegalPerson
Iteration: 1 Person Type: Tanane'FrontendBundle'Entity'NaturalPerson

为什么?错误在哪里?

您需要根据完全限定类名(FQCN)进行检查:

if ($person instanceof 'Tanane'FrontendBundle'Entity'NaturalPerson)

或者,您需要在文件顶部(命名空间下方)放置一个USE语句:

use Tanane'FrontendBundle'Entity'NaturalPerson;

所有Symfony类都是按名称空间命名的,因此如果类"NaturalPerson"与调用它的文件不在同一名称空间内,PHP将无法找到它

PHP命名空间