First of all I'm very new to OOP and I'm struggling big time. I have a question about the current design of my application and inheritance.
I have a bootstrapper file which initiates all my core classes, after including them, like this:
$security = new Security;
$error_handler = new ErrorHandler;
$application = new Application;
$mysql = new MySQL;
$template = new Template;
$user = new User;
I load the Security and ErrorHandler class first because the Application class needs them first (throw custom 404 errors, make GET variables safe etc). Now all classes extend the Application class, but I can't seem to call any data in any class from a child or parent class.
I read that I need to call the constructor of t开发者_运维技巧he parent class first to use any data. That's not really sexy and usefull in my eyes and I don't really see the use of using extends then.
Should I change the design? Or how could I use data from one to another class? I already tried composition but that ended up in a nightmare because I couldn't use any data of different child classes at all.
This is a weird set-up anyhow. You definitely should NOT be using some bootstrapper functionality to preload your classes, especially if certain classes have finite dependencies on other classes. What would be a bit better is this:
Your Security and ErrorHandler classes should use either static methods to allow their functionality to be used without declaring the class OR they should be created as a class var of the Application class.
class Security {
// can be invoked anywhere using Security::somefunction('blah');
public static somefunction($somevar) { ... }
}
OR
require_once('security.php');
require_once('errorhandler.php');
class Application {
public $security;
public $errorHandler;
public function __construct() {
$this->security = new Security;
$this->errorHandler = new ErrorHandler;
}
}
I'm not sure what you mean when you say that you can't access data from any class. Classes should naturally inherit any variables and functions that their parents have declared. So for example:
require_once('application.php');
class User extends Application {
public function throwError($message) {
return $this->errorHandler->somefunction($message);
}
}
Without expressly declaring $this->errorHandler
from within the User class, this should still work, as the $errorHandler
class var is declared in the Application class.
If you have a child-class that defines a __construct()
method, and want its parent's __construct()
method to be called, the __construct()
method of the child class must call the parent's one.
That's the way it is in PHP ; that's what you must do ; not much of a choice.
As a reference, quoting the Constructors and Destructors section of the manual :
Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to
parent::__construct()
within the child constructor is required.
精彩评论