错误:在控制器操作中调用 null 时的成员函数 create()

Posted

技术标签:

【中文标题】错误:在控制器操作中调用 null 时的成员函数 create()【英文标题】:Error: Call to a member function create() on null in controller action 【发布时间】:2019-03-10 19:30:33 【问题描述】:

这是我的控制器动作类

<?php
namespace Felix\HelloMod\Controller\Files;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class ProductFiles extends Action

    protected $_pagefactory;
    public function _construct(Context $context, PageFactory $pageFactory)
        $this->_pagefactory = $pageFactory;
        return parent::_construct($context);
    
    public function execute()
        return $this->_pagefactory->create();
    

我遇到以下错误:

致命错误:未捕获的错误:在 C:\xampp\htdocs\Mage2\app\code\Felix\HelloMod\Controller\Files\ProductFiles.php:15 调用成员函数 create() on null 堆栈跟踪:# 0 C:\xampp\htdocs\Mage2\generated\code\Felix\HelloMod\Controller\Files\ProductFiles\Interceptor.php(37): Felix\HelloMod\Controller\Files\ProductFiles->execute() #1 C:\ xampp\htdocs\Mage2\vendor\magento\framework\App\Action\Action.php(107): Felix\HelloMod\Controller\Files\ProductFiles\Interceptor->execute() #2 C:\xampp\htdocs\Mage2\供应商\magento\framework\Interception\Interceptor.php(58): Magento\Framework\App\Action\Action->dispatch(Object(Magento\Framework\App\Request\Http)) #3 C:\xampp\htdocs\ Mage2\vendor\magento\framework\Interception\Interceptor.php(138): Felix\HelloMod\Controller\Files\ProductFiles\Interceptor->___callParent('dispatch', Array) #4 C:\xampp\htdocs\Mage2\vendor \magento\framework\Interception\Interceptor.php(153): Felix\HelloMod\Controller\Files\ProductFiles\Interceptor->Magento\Framework\Interce ptionclosure(Object(Magento\Framework in C:\xampp\htdocs\Mage2\app\code\Felix\HelloMod\Controller\Files\ProductFiles.php 第 15 行

【问题讨论】:

$pageFactory 未定义。可能是因为它没有正确传递给类。 我想我确实在类定义之前在顶部定义了它。你建议我如何定义它。 你在哪里使用这个类?在那里,您需要检查是否将正确的参数传递给 ProductFiles 它的控制器动作类和它调用 create 方法,所以我不知道为什么会出现这个错误。 $pageFactory 来自哪里?它是未定义的。 【参考方案1】:

我错过了构造方法的双下划线并运行 php bin/magento setup:di:compile 并且它起作用了。

<?php
namespace Felix\HelloMod\Controller\Files;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class ProductFiles extends Action

    protected $_pagefactory;
    public function __construct(Context $context, PageFactory $pageFactory)
        $this->_pagefactory = $pageFactory;
        return parent::__construct($context);
    
    public function execute()
        return $this->_pagefactory->create();
    

【讨论】:

以上是关于错误:在控制器操作中调用 null 时的成员函数 create()的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 护照抛出错误:“在 null 上调用成员函数 createToken()”

Ajax 请求 500 错误 - 在 null 上调用成员函数

Laravel在null上调用成员函数isActivated()

Laravel 5 单元测试 - 在 null 上调用成员函数 connection()

Laravel:更新数据时在 null 上调用成员函数 getClientOriginalName()

致命错误:未捕获的错误:在 null 上调用成员函数 select()