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



我已经有一段时间没有在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);行。当我这样做时,页面加载 - 但是当我尝试在我需要它的控制器函数中调用它时,$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);
}

非常感谢建议或指点!

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

类具有 属性(类内的变量,并且对使用您已经阅读$this的所有方法都可见...(和

方法(函数(

<?php
namespace AppControllers;
use AppControllersBaseController; // Just guessing here
use AppModelsShopModel; // 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 AppControllers 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 AppViews?
echo view('templates/header', $data);
echo view('shop/view', $data);
echo view('templates/footer', $data);
}
}

要了解公共受保护,私有$this关键字的作用 - 阅读PHP类...你可以做到,这并不难。

$findall应该是一个类变量(在类内部声明,但在所有方法外部声明(,并使用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
];
....
}

最新更新