Codeigniter 4 构造函数,无法在其他函数中使用数据

Codeigniter 4 constructor, not able to use data in other functions

自从我在 CI 中使用构造函数以来已经有一段时间了。我查看了 CI4 的用户指南,构造函数似乎与 CI3 有点不同。我已经复制并试用了代码,但收到错误消息:Cannot call constructor.

    public function __construct(...$params)
    {
        parent::__construct(...$params);

        $model = new ShopModel();

        $findAll = [
            'shop' => $model->table('shop')->where('brand_name_slug', 'hugo-boss')->findAll()
        ];
    }

从这里开始,我在网上搜索并看到一个类似的帖子,建议完全删除 parent::__construct(...$params); 行。当我这样做时,页面加载 - 但是当我尝试在 Controller 函数中调用它时 $findAll 数组为 NULL 我需要它:

    public function brand_name($brand_name_slug)
    {
        $model = new ShopModel();

        var_dump($findAll['shop']);

        $data = [
            'shop' => $findAll['shop'],
        ];

        echo view('templates/header', $data);
        echo view('shop/view', $data);
        echo view('templates/footer', $data);
    }

非常感谢建议或指点!

$findall 应该是一个 class 变量 (在 class 内部声明但在所有方法之外)和 accessed/modified使用 this 关键字,如下所示:

Class Your_class_name{

 private $findAll;  //This can be accessed by all class methods

 public function __construct()
    {
        parent::__construct();

        $model = new ShopModel(); //Consider using CI's way of initialising models

        $this->findAll = [
            'shop' => $model->table('shop')->where('brand_name_slug', 'hugo-boss')->findAll()
        ]; //use the $this keyword to access class variables
    }


public function brand_name($brand_name_slug)
    {
        ...

        $data = [
            'shop' => $this->findAll['shop'], //use this keyword
        ];

        ....
    }

好吧,这是另一个答案,有点开玩笑。

一个Class有 Properties(class 内的变量,对所有使用 $this 的方法可见,您已经阅读过...)和

方法(函数)

<?php
namespace App\Controllers;
use App\Controllers\BaseController; // Just guessing here
use App\Models\ShopModel; // Just guessing here

class YourClass extends BaseController {

    // Declare a Property - Its a PHP Class thing...

    protected $findAll; // Bad Name - What are we "Finding"?

    public function __construct()
    {
        // parent::__construct(); // BaseController has no Constructor

        $model = new ShopModel(); // I am guessing this is in your App\Controllers Folder.

        // Assign the model result to the badly named Class Property
        $this->findAll = [
            'shop' => $model->table('shop')->where('brand_name_slug', 'hugo-boss')->findAll()
        ];
    }


    public function brand_name($brand_name_slug)
    {
        var_dump($this->findAll['shop']);

        $data = [
            'shop' => $this->findAll['shop'],
        ];

        // Uses default App\Views\?
        echo view('templates/header', $data);
        echo view('shop/view', $data);
        echo view('templates/footer', $data);
    }
}

找出publicprotectedprivate$this 关键字 - 阅读 PHP Classes...你可以做到,这并不难。