Codeigniter 4构造函数,不能在其他函数中使用数据。

问题描述 投票:0回答:1

我已经很久没有在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);
    }

非常感谢您的建议或指导!

codeigniter constructor controller construct codeigniter-4
1个回答
1
投票

$findall 应该是一个 类变量 (在类内部声明,但在所有方法之外),并使用 这个 这样的关键词。

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
        ];

        ....
    }

1
投票

好吧,这里有另一个答案,有点口无遮拦。

A类有 属性 (类内的变量,对所有使用$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);
    }
}

要了解什么是 公共, 受保护私人这个 关键字做--读懂PHP类... 你可以做到的,这并不难。

© www.soinside.com 2019 - 2024. All rights reserved.