HomePHP Page 3 - Abstract Classes in PHP: Working with PHP 5
Calling class methods out of the object context: using the scope resolution operator - PHP
Here we are again. This is the tutorial you’ve been waiting for! Welcome to the last part of the series “Abstract classes in PHP.” If you’ve already read the previous articles, then you’ll know that this series introduces the basics of abstract classes in PHP 4/PHP 5, and illustrates their use and implementation in concrete situations.
As I explained before, you can declare a class abstract, and possibly even call their methods without raising a fatal error. Of course, this process is rather pointless and unusual, but for the sake of completeness, here’s how I’d call the methods of the sample abstract class you saw right at the beginning of the article, by using the scope resolution operator:
abstract class Message{ private static $message; public function setMessage($message){ if(!is_string($message)){ throw new Exception('Invalid parameter type!'); } self::$message=$message; } public function fetchMessage(){ return self::$message; } } try{ // call 'setMessage()' method out of object context Message::setMessage('This is an abstract PHP 5 class, and its methods are called out of the object context.'); echo Message::fetchMessage(); } catch(Exception $e){ echo $e->getMessage(); exit(); }
As you can see, the above example uses the double colon operator (also called Paamayim Nekudotayim, or double-colon in Hebrew), in order to call the class methods without raising a fatal error. However, in most cases abstract classes must include abstract methods, which turns the above snippet into a rather inefficient method for using an abstract class, since all its methods are explicitly implemented.
At this stage, I hope you understand how to define an abstract class in PHP 5. However, all the theory that you just learned is rather useless if I don’t show you a concrete case. It’s precisely for this reason that over the next few lines, I’ll set up an illustrative example. Thus you can grasp the concepts for using abstract classes in PHP 5. Click the link and keep reading.