在非对象 /app/code/core/Mage/Core/Block/Template.php(241) 上调用成员函数 getId()

Call to a member function getId() on a non-object /app/code/core/Mage/Core/Block/Template.php(241)

我知道通常 "call to a member function" 错误是因为对象的 class 没有扩展适当的父 class。但是,我的 NS_Module_Block_File class 已经扩展 Mage_Catalog_Block_Product_View。我的代码在 file.phtml:

$object = Mage::getSingleton('catalog/product');
$_product = $object->loadByAttribute('sku','P01');
$id = $_product->getId();

我也把它放在我的主题中 local.xml:

<ns_module_file_index>
    <reference name="root">
        <action method="setTemplate"><template>page/1column.phtml</template></action>
    </reference>
    <reference name="content">
        <block type="ns_module/file" name="module.file" template="file.phtml" />
    </reference>
</ns_module_file_index>

我不确定问题出在哪里。请帮忙。提前谢谢你。

试试这个:

$_product = Mage::getModel('catalog/product')->loadByAttribute('sku','P01');

如果您查看 loadByAttribute 的方法:

public function loadByAttribute($attribute, $value, $additionalAttributes = '*')
{
    $collection = $this->getResourceCollection()
        ->addAttributeToSelect($additionalAttributes)
        ->addAttributeToFilter($attribute, $value)
        ->setPage(1,1);

    foreach ($collection as $object) {
        return $object;
    }
    return false;
}

如果sku"P01"的商品不存在,则不会返回对象,因为集合为空;将返回 false。