PHP
  Home arrow PHP arrow Page 2 - Abstract Classes in PHP: Working with ...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Abstract Classes in PHP: Working with PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 23
    2006-02-08

    Table of Contents:
  • Abstract Classes in PHP: Working with PHP 5
  • Working with a highly improved object model: defining abstract classes in PHP 5
  • Calling class methods out of the object context: using the scope resolution operator
  • Using abstract classes in PHP 5: setting up an example

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Abstract Classes in PHP: Working with PHP 5 - Working with a highly improved object model: defining abstract classes in PHP 5


    (Page 2 of 4 )

    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


       · If you've been reading the previous articles of this series, probably you'll find...
     

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway
    Stay green...Green IT