Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including a class within another class in php

Tags:

include

php

class

I have a class 'search' which is only used under sertain circumstances. The decision whether 'search' is needed or not is made in the class 'page' in the function 'setupPage'. Is it okay (is it good coding), to include a class within another class?

class Page {
    private function setupPage($page_id){
        switch($page_id){
            case 1:
            // do something
            break;

            case 2:
            include_once('class_search.php');
            // class search is singleton
            $this->search = Search::getInstance();
            // now I can use functions of 'search'
            $this->search->someSearchFunction();
        }
    }
}
like image 312
esviko Avatar asked Jan 30 '26 14:01

esviko


2 Answers

it is absolutely fine to do so, but you have other alternative too. you might want to look at php's autoloading function

function __autoload($class_name) {
    include $class_name . '.php';
}

whenever you instantiate a new class. PHP automagically calls the __autoload function with one argument i.e the class name. consider the below example

$user = new User():

when you instantiate the user object here the autoload function is called, it tries include the file from the same directory. (with reference to above autoload function). now you could implement your own logic to autoload classes. no matter in which directory it resides. for more information check out this link http://in.php.net/autoload.

like image 181
Ibrahim Azhar Armar Avatar answered Feb 01 '26 02:02

Ibrahim Azhar Armar


I wouldn't do this. If you want your classes only be loaded, if they are needed, I suggest you use PHP's autoloading for this. Here is the Documentation.

like image 40
Basti Avatar answered Feb 01 '26 04:02

Basti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!