PHP includes a class in another class

I study OOP and am very confused about using classes for each other.

I have only 3 classes

//CMS System class class cont_output extends cont_stacks { //all methods to render the output } //CMS System class class process { //all process with system and db } // My own class to extends the system like plugin class template_functions { //here I am using all template functions //where some of used db query } 

Now I want to use my own template_functions class with both system classes. But it is very vague how to use it. Please help me figure this out.

EDIT: I'm sorry I forgot to mention that my own class is in another PHP file.

+6
source share
2 answers

First of all, make sure you include class file before using it:

 include_once 'path/to/tpl_functions.php'; 

This should be done either in your index.php, or on top of a class that uses tpl_function . Also note the possibility of autoloading classes:

With PHP5, you should be able to automatically load classes. This means that you register a hook function that is called every time you try to use the class, the code file is not yet included. To do this, you do not need to include_once statements in each class file. Here is an example:

index.php or any application entry point:

 spl_autoload_register('autoloader'); function autoloader($classname) { include_once 'path/to/class.files/' . $classname . '.php'; } 

Now you can access the classes without worrying about including code files. Try:

 $process = new process(); 

Knowing this, there are several ways to use the template_functions class


Just use it:

You can access the class anywhere in the code if you instantiate it:

 class process { //all process with system and db public function doSomethging() { // create instance and use it $tplFunctions = new template_functions(); $tplFunctions->doSomethingElse(); } } 

Members of the instance:

Take a process class, for example. To make template_functions available inside the process class, you create an instance member and initialize it somewhere where you need it, the constructor seems to be a good place:

 //CMS System class class process { //all process with system and db // declare instance var protected tplFunctions; public function __construct() { $this->tplFunctions = new template_functions; } // use the member : public function doSomething() { $this->tplFunctions->doSomething(); } public function doSomethingElse() { $this->tplFunctions->doSomethingElse(); } } 
+10
source

You can extend the template_functions class, then you can use all the functions.

 class cont_output extends cont_stacks //cont_stacks has to extend template_functions { public function test() { $this->render(); } } class process extends template_functions { public function test() { $this->render(); } } class template_functions { public function render() { echo "Works!"; } } 
0
source

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


All Articles