As I anticipated in the segment that you just read, one of the simplest ways to use the “Loader” class without having to create an instance of it consists of calling its “load()” method out of the object context, or in other words, statically. PHP does support calling a non-static method statically (which is not supported when using static class properties), but to assure that the “load()” method will always be invoked statically, I’m going to refactor the class, this time declaring the method obviously static. Does all of this jargon sound a bit confusing to you? Fear not. Only pay attention to the enhanced version of the “Loader” class, after implementing this subtle change. Here it is: // define the loader class (the 'load()' method is declared static) class Loader { // constructor (not implemented) public function __construct(){}
// load specified file public static function load($filepath) { if (!file_exists($filepath)) { throw new Exception('The specified file cannot be found!'); } require_once($filepath); } } That was easy to code and read, wasn’t it? As you can see, now the “Loader” class looks nearly identical to its previous version, except for one small but crucial modification: its “load()” method has been declared static explicitly via the “static” keyword. This means that if the method is eventually called in the object scope (read dynamically), the PHP engine will complain loudly about this and throw an error. Naturally, the most evident benefit in declaring this method static is that there’s no need to spawn an instance of the “Loader” class to call it. In this case, I’m getting the best of both worlds: I’m still able to include files using the “load()” method, but no object needs to be created. However, the best way to understand the nitty-gritty of this process is by coding a concrete example. So, the last section of this tutorial will be dedicated to develop that example, so you can see how the improved version of the “Loader” class is really much more flexible and efficient. Thus, don’t waste more time; read the following segment. It’s only one click away.
blog comments powered by Disqus |
|
|
|
|
|
|
|