php - Fatal error: Uncaught Error: Typed property must not be accessed before initialization
Get the solution ↓↓↓i cant figure out why im getting this error message:
Fatal error: Uncaught Error: Typed property App\Controller\products::$ProductRepository must not be accessed before initialization in /mnt/c/mvc/src/Controller/products.php:24 Stack trace: #0 /mnt/c/mvc/index.php(21): App\Controller\products->action() #1 {main} thrown in /mnt/c/mvc/src/Controller/products.php on line 24
i hope someone can explain me why this error is thrown, thanks in advance!
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) {
}
}
}
Im trying to get an array out of a JSON File and im not sure if this is the right way to do it but my main problem is thiss error message.
I hope some of you guys can show me the direction to search in. Thanks in advance!
Answer
Solution:
To access methodgetList()
fromclass ProductRepository
you need to create an object. Do this in the constructor ofclass 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) {
}
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: foreign key constraint is incorrectly formed laravel
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.