【问题标题】:Fatal error: Uncaught Error: Typed property must not be accessed before initialization致命错误:未捕获错误:在初始化之前不得访问类型化属性
【发布时间】:2021-02-27 11:45:41
【问题描述】:

我不知道为什么会收到此错误消息:

致命错误:未捕获错误:在 /mnt/c/mvc/src/Controller/products.php:24 中初始化之前不得访问类型属性 App\Controller\products::$ProductRepository 堆栈跟踪:#0 /mnt /c/mvc/index.php(21): App\Controller\products->action() #1 {main} 在第 24 行的 /mnt/c/mvc/src/Controller/products.php 中抛出

希望有人能解释一下为什么会抛出这个错误,在此先感谢!

ProductRepository.php

class ProductRepository
{
   private array $ProductList;

   public function getList(): array
   {
       $productJson = file_get_contents('model.json');

       $decodedProductList = json_decode($productJson, true);

       return explode(', ', $decodedProductList);
}

products.php

class products extends PageController
{
   private ProductRepository $ProductRepository;

   public function action(): void
   {
       $this->smarty->assign('headline', 'PRODUCTS');
       $this->smarty->assign('info', 'Product Overview');
       $this->smarty->assign('name', 'Every Product!');
       $this->smarty->assign('LIST', $this->ProductRepository->getList());

       try {
           $this->smarty->display('products.tpl');
       } catch (\SmartyException $e) {
       } catch (\Exception $e) {
       }
   }
}

我试图从 JSON 文件中获取一个数组,但我不确定这是否是正确的方法,但我的主要问题是这个错误消息。

我希望你们中的一些人能告诉我搜索的方向。 提前致谢!

【问题讨论】:

  • 您在哪里实际设置了$ProductRepository 属性?除非您在该属性中存储一个对象,否则您将无法将其用作一个对象。使用 ProductRepository 提示的类型不会创建实际实例。
  • 我不明白你所说的set是什么意思?这是我从 JSON 文件中获取数据的类的名称。如何创建它的实际实例?
  • 您是否尝试过显而易见的选择,即。新的 ProductRepository() ?
  • 您必须先设置$ProductRepository 属性,然后才能将其与$this->ProductRepository 一起使用。在构造函数中使用 ProductRepository 类的实例设置属性似乎是要走的路。

标签: php asp.net-mvc


【解决方案1】:

要从class ProductRepository 访问方法getList(),您需要创建一个对象。在class products 的构造函数中执行此操作。

<?php
class products extends PageController
{
    private ProductRepository $ProductRepository;

    public function __construct()
    {
        $this->ProductRepository = new ProductRepository(); // you now have access to the public methods of ProductRepository
    }

    public function action(): void
    {
        $this->smarty->assign('headline', 'PRODUCTS');
        $this->smarty->assign('info', 'Product Overview');
        $this->smarty->assign('name', 'Every Product!');
        $this->smarty->assign('LIST', $this->ProductRepository->getList());

        try {
            $this->smarty->display('products.tpl');
        } catch (\SmartyException $e) {
        } catch (\Exception $e) {
        }
    }
}

【讨论】:

  • maan 也许我应该去睡觉了...谢谢!
  • 很高兴我能帮上忙!
猜你喜欢
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
相关资源
最近更新 更多