A simple method for coding a class that can’t be instantiated consists of including a simple “die()” statement inside its constructor. The example below demonstrates a simple way to implement this method: class baseClass { function baseClass(){ die('This class is abstract. It cannot be instantiated!'); } } // try to instantiate abstract class $baseclass=&new baseClass(); The above example shows a very simple approach to preventing a class from being instantiated, by including a “die()” statement within the class constructor. After trying to instantiate an object from the sample “baseClass”, I get the following message: This class is abstract. It cannot be instantiated! And logically, the script is simply halted. Moreover, the above method is also effective if I ever want to statically call the constructor, by using the resolution scope operator (::), as listed below: baseClass::baseClass(); This class is abstract. It cannot be instantiated! In this case, the “die()” statement again displays a warning message and stops the execution of the script. For the first attempt at creating an abstract class, it’s not bad at all. However, a “die()” statement does not provide much control on program execution, so let’s move on and code another example of an abstract class. This time, we'll use the “trigger_error()” PHP built-in function. Have a look: class baseClass { Fatal error: This class is abstract. It cannot be instantiated! in path/to/file As shown by the above example, I’ve coded the sample class so it triggers a fatal error whenever there’s an attempt to instantiate it. Here, I’ve used the magic constant __CLASS__ in order to prevent the class from being instantiated, which raises a fatal error when this happens. Similar to the first example you saw earlier, if I ever want to statically call the class constructor, I get the same result: baseClass::baseClass(); Fatal error: This class is abstract. It cannot be instantiated! in path/to/file So far, I’ve defined a sample class that triggers a fatal error and, in consequence, halts the script when trying to spawn an object from it. This means that I’m very close to defining an abstract class in PHP 4. However, there are some issues to be addressed yet. The current definition of the sample class doesn’t prevent calling the constructor from a non child class. Taking this limitation into account, the next few lines will show you how to fix this problem. Scroll down the page and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|