php - 使用 "instanceof"的正确方法是什么?

标签 php symfony

我有这个代码:

$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;
}

但是每当我运行该函数时,我都会收到此错误:

Attempted to call method "getRIF" on class "Tanane\FrontendBundle\Entity\NaturalPerson" in /var/www/html/tanane/src/Tanane/BackendBundle/Controller/OrderController.php line 114. Did you mean to call: "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 Namespaces

关于php - 使用 "instanceof"的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25799555/

相关文章:

php - 将错误保存到 MySQL 数据库

c# - 如何从网页运行 Windows 应用程序?

php - 如何用 PHP 替换字符串中的变量?

javascript - 为什么 Bootstrap Js 在我的模板中不起作用?

javascript - Symfony 4 - 无法在 formBuilder 中自定义表单字段的 attr

symfony - 在实体表单字段中创建查询

css - 将类添加到 symfony 复选框的子集

regex - 使用Symfony验证电话号码

php - 使用在 WordPress 中存储为逗号分隔的元键和元值搜索用户

PHP+1 真的加了两个