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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With