gpt4 book ai didi

PHP 以类作为值提取数组

转载 作者:可可西里 更新时间:2023-11-01 13:22:38 25 4
gpt4 key购买 nike

我正在开发一个 MVC 框架,但我在声明帮助类时遇到了一个灵活的代码/结构的问题

class Controller {
public $helper = [];

public function load_helper($helper) {
require_once(DIR_HELPER . $helper . '.php');
$lc_helper = StrToLower($helper);
$helper_arr[$lc_helper] = new $helper;
$this->helper[$lc_helper] = $helper_arr[$lc_helper];
}
}

//我在 Controller 中这样调用函数

Class Home Extends Controller   {

$this->load_helper('Form');

$this->helper['form']-><class function>;
}

我想这样调用函数:

$this->form-><class function>;

我不能对公共(public)函数使用提取,但我见过可以做到这一点的框架。

我希望有人有想法并且有人可以理解我的问题,在此先感谢。

最佳答案

看看魔法__get方法。来自文档:

Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.

The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms "inaccessible properties" and "inaccessible methods" to refer to this combination of declaration and visibility.

例如可以这样实现:

class Controller {
public $helper = [];

public function load_helper($helper) {
require_once(DIR_HELPER . $helper . '.php');
$lc_helper = StrToLower($helper);
$helper_arr[$lc_helper] = new $helper;
$this->helper[$lc_helper] = $helper_arr[$lc_helper];
}

public function __get($property) {
//Load helper if not exists
if (!isset($this->helper[$property])) {
$this->load_helper($property);
}

//Return the helper
return $this->helper[$property];
}
}

旁注:

Controller::$helperController::load_helper() 在我的理解中应该是 privateprotected 而不是 public

关于PHP 以类作为值提取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30022267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com