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();
}
}
}
it is absolutely fine to do so, but you have other alternative too. you might want to look at php’s autoloading function
whenever you instantiate a new class. PHP automagically calls the
__autoloadfunction 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.