esviko
esviko

Reputation: 358

Including a class within another class in php

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();
        }
    }
}

Upvotes: 3

Views: 123

Answers (3)

Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

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.

Upvotes: 2

Alexander Varwijk
Alexander Varwijk

Reputation: 2083

This shouldn't be a problem, if you use autoloading this very thing would be happening.

Upvotes: 0

Basti
Basti

Reputation: 4042

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.

Upvotes: 2

Related Questions