PHP
  Home arrow PHP arrow Page 3 - Enforcing Object Types in PHP: Using the Type Hinting Feature in 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

Enforcing Object Types in PHP: Using the Type Hinting Feature in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 3
    2006-03-01


    Table of Contents:
  • Enforcing Object Types in PHP: Using the Type Hinting Feature in PHP 5
  • The “Type Hinting” feature of PHP 5: taking an in-depth look
  • A practical example: using “Type Hinting” within a web page generator class
  • Putting “Type Hinting” to work: building object-based web documents

  • 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


    Enforcing Object Types in PHP: Using the Type Hinting Feature in PHP 5 - A practical example: using “Type Hinting” within a web page generator class
    ( Page 3 of 4 )

    In order to utilize the web page generator class that I wrote in my previous article, let me first list the set of (X)HTML widget classes, useful for rendering page elements. As you’ll recall, these widget classes looked like this:

    // define abstract class HTMLElement
    abstract class HTMLElement{
        protected $attributes;
        protected function __construct($attributes){
            if(!is_array($attributes)){
                throw new Exception('Invalid attribute type');
            }
            $this->attributes=$attributes;
        }
        // abstract 'getHTML()' method
        abstract protected function getHTML();
    }
    class Div extends HTMLElement{
        private $output='<div ';
        private $data;
        public function __construct($attributes=array(),$data){
            if(!$data instanceof HTMLElement&&!is_string($data)){
                throw new Exception('Invalid parameter type');
            }
            parent::__construct($attributes);
            $this->data=$data;
        }
        // concrete implementation for 'getHTML()' method
        public function getHTML(){
            foreach($this->attributes as $attribute=>$value){
                $this->output.=$attribute.'="'.$value.'" ';
            }
            $this->output=substr_replace($this->output,'>',-1);
            $this->output.=($this->data instanceof HTMLElement)?
    $this->data->getHTML():$this->data;
            $this->output.='</div>';
            return $this->output;
        }
    }
    class Header1 extends HTMLElement{
        private $output='<h1 ';
        private $data;
        public function __construct($attributes=array(),$data){
            if(!$data instanceof HTMLElement&&!is_string($data)){
                throw new Exception('Invalid parameter type');
            }
            parent::__construct($attributes);
            $this->data=$data;
        }
        // concrete implementation for 'getHTML()' method
        public function getHTML(){
            foreach($this->attributes as $attribute=>$value){
                $this->output.=$attribute.'="'.$value.'" ';
            }
            $this->output=substr_replace($this->output,'>',-1);
            $this->output.=($this->data instanceof HTMLElement)?
    $this->data->getHTML():$this->data;
            $this->output.='</h1>';
            return $this->output;
        }
    }
    class Paragraph extends HTMLElement{
        private $output='<p ';
        private $data;
        public function __construct($attributes=array(),$data){
            if(!$data instanceof HTMLElement&&!is_string($data)){
                throw new Exception('Invalid parameter type');
            }
            parent::__construct($attributes);
            $this->data=$data;
        }
        // concrete implementation for 'getHTML()' method
        public function getHTML(){
            foreach($this->attributes as $attribute=>$value){
                $this->output.=$attribute.'="'.$value.'" ';
            }
            $this->output=substr_replace($this->output,'>',-1);
            $this->output.=($this->data instanceof HTMLElement)?
    $this->data->getHTML():$this->data;
            $this->output.='</p>';
            return $this->output;
        }
    }
    class UnorderedList extends HTMLElement{
        private $output='<ul ';
        private $items=array();
        public function __construct($attributes=array(),$items=array
    ()){
            parent::__construct($attributes);
            if(!is_array($items)){
                throw new Exception('Invalid parameter for list
    items');
            }
            $this->items=$items;
        }
        // concrete implementation for 'getHTML()' method
        public function getHTML(){
            foreach($this->attributes as $attribute=>$value){
                $this->output.=$attribute.'="'.$value.'" ';
            }
            $this->output=substr_replace($this->output,'>',-1);
            foreach($this->items as $item){
                $this->output.=($item instanceof
    HTMLElement)?'<li>'.$item->getHTML().'</li>':'<li>'.$item.'</li>';
            }
            $this->output.='</ul>';
            return $this->output;
        }
    }

    After defining the bunch of (X)HTML widget classes, which were originally created as subclasses of the abstract “HTMLElement” class, it’s time to list the web page generator class in question. Remember that it also uses the “instanceof” operator within its “addHTMLElement” method, in order to accept only objects of type “HTMLElement.”  The code listed below should refresh your memory of how this class looks:

    class PageGenerator{
        private $output='';
        private $title;
        public function __construct($title='Default Page'){
            $this->title=$title;
        }
        public function doHeader(){
            $this->output='<html><head><title>'.$this-
    >title.'</title></head><body>';
        }
        public function addHTMLElement($htmlElement){
            if(!$htmlElement instanceof HTMLElement){
                throw new Exception('Invalid (X)HTML element');
            }
            $this->output.=$htmlElement->getHTML();
        }
        public function doFooter(){
            $this->output.='</body></html>';
        }
        public function fetchHTML(){
            return $this->output;
        }
    }

    Now, did you recall the signature for the above class? Fine, now allow me introduce a small change into its definition, particularly within its “addHTMLElement()” method, by replacing the corresponding “instanceof” operator with the “Type Hinting” feature:

    class PageGenerator{
        private $output='';
        private $title;
        public function __construct($title='Default Page'){
            $this->title=$title;
        }
        public function doHeader(){
            $this->output='<html><head><title>'.$this-
    >title.'</title></head><body>';
        }
        // type hinting is applied to input objects
        public function addHTMLElement(HTMLElement $htmlElement){
            $this->output.=$htmlElement->getHTML();
        }
        public function doFooter(){
            $this->output.='</body></html>';
        }
        public function fetchHTML(){
            return $this->output;
        }
    }

    At this point, you’ll agree with me that the improved class listed above looks very interesting now. Notice the implementation of “Type Hinting” within the pertinent “addHTMLElement()” method, in order to force all objects to be of type “HTMLElement”:

    public function addHTMLElement(HTMLElement $htmlElement){
        $this->output.=$htmlElement->getHTML();
    }

    Now that you know how “Type Hinting” has been implemented within the web page generator class you saw above, the next thing to do is set up an example, which hopefully will demonstrate the advantages of this handy feature. Therefore, go ahead and read the next 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 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek