Php 如何禁止致命错误:调用成员函数?

Php 如何禁止致命错误:调用成员函数?,php,magento,Php,Magento,可能重复: 致命错误:对中的非对象调用成员函数getParentCategory 守则: $_category_detail=Mage::registry('current_category'); $id=$_category_detail->getParentCategory()->getId(); 现在,当页面无法使用getParentCategory i时,请使用以下命令,但无法工作 if( isset(getParentCategory()){ $id

可能重复:

致命错误:对中的非对象调用成员函数getParentCategory

守则:

$_category_detail=Mage::registry('current_category');
$id=$_category_detail->getParentCategory()->getId(); 
现在,当页面无法使用getParentCategory i时,请使用以下命令,但无法工作

 if( isset(getParentCategory()){
        $id=$_category_detail->getParentCategory()->getId();  
    }
为什么??谢谢

看来$\u category\u detail不是一个对象。因此,Mage::registry'current_category'没有返回对象

它很可能在失败时返回某种NULL或false值。PHP让您注意到NULL->getParentCategory毫无意义

在您的特定情况下,它返回NULL,因为您的注册表中未设置当前的\u类别。

您需要使用方法\u exists,而不是尝试调用不存在的函数:

if (method_exists($_category_detail, "getParentCategory"))

isset只检查成员变量。使用方法_存在

PHP手册:


如果$\u category\u detail不是有效的对象,它不会触发错误吗?它不会-只是自己测试它。。。既不记录也不测试,也不触发错误;只返回false
if (method_exists($_category_detail, 'getParentCategory')) {
    $id = $_category_detail->getParentCategory()->getId()
}