PHP Retrieving an Array with a Class as a Value

I am developing an MVC framework and I have a problem creating flexible code / framework when declaring helper classes

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

// I call the function in my controllers, e.g.

 Class Home Extends Controller { $this->load_helper('Form'); $this->helper['form']-><class function>; } 

I want to call a function as follows:

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

I cannot use extraction for public functions, but I have seen frameworks that can do this.

I hope someone has an idea and someone can understand my question, thanks in advance.

+6
source share
1 answer

Take a look at the __get magic method. From the documentation:

PHP overloading provides a means to dynamically create properties and methods. These dynamic objects are processed using magic methods you can set in the class for various types of actions.

Overload methods I nvoked when interacting with properties or methods that have not been declared or are not displayed in the current scope. The rest of this section will use the terms “inaccessible properties” and “inaccessible methods” to mean this combination of declaration and visibility.

This can be implemented, for example, as follows:

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

Side note:

Controller::$helper and Controller::load_helper() in my understanding should be private or protected instead of public .

+5
source

Source: https://habr.com/ru/post/986468/


All Articles