浏览文章

文章信息

【Magento2】 PHP Fatal error: Uncaught Error: Call to a member function getAreaCode() on null 17225

来欣赏下源码:

namespace Aiweline\ProductView\Block;
use Magento\Framework\View\Element\Template;
class Contact extends Template
{
    const type_CONTACT = 'contact';
    private $helper;
    function __construct(
        \Aiweline\ProductView\Helper\Data $helper
    ) {
        $this->helper = $helper;
    }
    function getHtml(string $type){
       return $this->helper->getConfig($type.'/html');
    }
}

对比下面的代码发现什么没有?

namespace Aiweline\ProductView\Block;
use Magento\Framework\View\Element\Template;
class Contact extends Template
{
    const type_CONTACT = 'contact';
    private $helper;
    function __construct(
        \Aiweline\ProductView\Helper\Data $helper,
        \Magento\Framework\View\Element\Template\Context $context,
        array $data = []
    ) {
        $this->helper = $helper;
        parent::__construct($context, $data);
    }
    function getHtml(string $type)
    {
        return $this->helper->getConfig($type . '/html');
    }
}

经过对比,我们发现,模板没有上下文管理Context,也就是没有继承父类的

parent::__construct($context, $data);

没了上下文,Magento Template在解析areacode时调用了不存在的Context上下文,所以getAreaCode() on null

原创