Home arrow PHP arrow Page 2 - Abstract Classes in PHP: Working with PHP 5

Working with a highly improved object model: defining abstract classes in PHP 5 - 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.

TABLE OF CONTENTS:
  1. Abstract Classes in PHP: Working with PHP 5
  2. Working with a highly improved object model: defining abstract classes in PHP 5
  3. Calling class methods out of the object context: using the scope resolution operator
  4. Using abstract classes in PHP 5: setting up an example
By: Alejandro Gervasio
Rating: starstarstarstarstar / 50
February 08, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Because of the numerous improvements introduced in its Object Model, PHP 5 makes it much easier to work with abstract classes. The process is as simple as preceding the “class” keyword with the term “abstract” and following certain prerequisites that should be met (more about this in a moment). Of course, as with PHP 4, abstract classes in PHP 5 cannot be instantiated, and any attempt to instantiate them will result in a fatal error triggered by the PHP interpreter.

Right, that’s the explanation of the theory. Now, let me show you a regular PHP 5 class and next, allow me to demonstrate how I can turn it into an abstract one. Look at the following example:

class Message{
    private $message;
    public function __construct($message){
        if(!is_string($message)){
            throw new Exception('Invalid parameter type!');
        }
        $this->message=$message;
    }
    public function fetchMessage(){
        return $this->message;
    }
}
try{
    // instantiate '$message' object
    $message=new Message('This is a regular PHP 5 class.');
    echo $message->fetchMessage();
}
catch(Exception $e){
    echo $e->getMessage();
    exit();
}

As you can see, this isn’t rocket science. What I’ve done above is simply define a regular PHP 5 class, which only displays string messages, passed on as a parameter to its constructor. So far, it’s nothing unexpected, so I’ll go one step further and turn this class into an abstract one. Take a look:

abstract class Message{
    private $message;
    public function __construct($message){
        if(!is_string($message)){
            throw new Exception('Invalid parameter type!');
        }
        $this->message=$message;
    }
    public function fetchMessage(){
        return $this->message;
    }
}
try{
    // try to instantiate '$message' object - throws a fatal
error
    $message=new Message('This is an abstract PHP 5 class.');
    echo $message->fetchMessage();
}
catch(Exception $e){
    echo $e->getMessage();
    exit();
}

 

Here, there are a few interesting things worth noting. First, if you run the above script, you’ll be faced with a fatal error. Since the sample class is now declared abstract, it’s not possible to perform its instantiation, a fact the PHP parser will let you know by raising a fatal error and halting the script.

Of course, the second thing to notice is the simple inclusion of the “abstract” keyword, in order to indicate to the interpreter what type of class I intend to work with. In this case, I’ve kept the class code intact, so you can easily understand the whole definition process, but it’s rather pointless and a bad programming habit to provide specific implementation for all the class methods.

In addition, there are some rules that must be followed, which surely will make your life easier when working with abstract classes in PHP 5. First, if you define an abstract method inside any class, the containing class must be abstract as well. Otherwise, a fatal error will be triggered.

Second, according to what you learned in my previous article, abstract methods only declare the signature; they do not provide explicit implementation. And finally, if you derive a subclass that implements an abstract method, the visibility of this method must be the same or weaker than the one specified in the parent class. Maybe this sounds like a convoluted thing, but don’t feel concerned right now. At the moment of coding the corresponding examples, the above rules should become clear to you.

Fine, now you know how to declare an abstract class in PHP 5. However, perhaps you’re wondering: is there any way to call the methods of an abstract class, without getting a fatal error? Well, even when this isn’t actually a desirable thing, there are times when you need to call a method out of the object context, by using the (::) scope resolution operator. To find out how this is done, please read the following section.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: