PHP
  Home arrow PHP arrow Page 2 - Abstract Classes in PHP: Working with PHP 5
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PHP

Abstract Classes in PHP: Working with PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 31
    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:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek