我有这个代码:
$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 - 使用 "instanceof"的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25799555/