PHP
  Home arrow PHP arrow Page 3 - Enforcing Object Types in PHP: Using the PHP5 instanceof Operator
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? 
PHP

Enforcing Object Types in PHP: Using the PHP5 instanceof Operator
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 7
    2006-02-22


    Table of Contents:
  • Enforcing Object Types in PHP: Using the PHP5 instanceof Operator
  • Checking object types in PHP 5: what you shouldn’t do
  • Forcing object types in PHP 5: using the “instanceof” operator
  • Extending the use of the “instanceof” operator: nesting (X)HTML widgets

  • 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 PHP5 instanceof Operator - Forcing object types in PHP 5: using the “instanceof” operator
    ( Page 3 of 4 )

    As you’ll see, the “instanceof” operator is very simple to use. It takes two arguments for doing its business. The first one on the left is the object you want to check, while the second one, placed on the right, is the name of the class (or eventually an interface name) used for determining if the object in question is “an instance of” the pertinent class. Of course, I deliberately used the above terms, thus you can see how intuitive this operator is. Its basic syntax is as follows:

    if (object instanceof class name){
        // do something useful
    }

    Now that you know how this operator is used in PHP 5, let’s redefine the corresponding web page generator class, in order to verify the type of objects passed to its “addHTMLElement()” method. Here’s the new signature for this class, which as I mentioned before, uses the “instanceof” operator:

    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;
        }
    }

    Please notice in the above class how the “instanceof” operator is included inside the “addHTMLElement()” method, in order to make sure that all the objects passed in are instances of the “HTMLElement” class, defined earlier. Now, it’s possible to rebuild the web page you saw previously, in this case making sure that all the input objects pushed into the web page generator class are true (X)HTML widget objects. Here’s the corresponding example:

    try{
        // spawn some HTML elements
        $h1=new Header1(array('name'=>'header1','class'=>'headerclass'),'Content for H1 element goes here');
        $div=new Div(array('name'=>'div1','class'=>'divclass'),'Content for Div element goes here');
        $par=new Paragraph(array('name'=>'par1','class'=>'parclass'),'Content for Paragraph element goes here');
        $teststr=’This is not a HTML element’;
        // instantiate page generator class 
        $pageGen=new PageGenerator();
        $pageGen->doHeader();
        // add 'HTMLElement' objects
        $pageGen->addHTMLElement($teststr) //pass simple string to this method
        $pageGen->addHTMLElement($h1);
        $pageGen->addHTMLElement($div);
        $pageGen->addHTMLElement($par);
        $pageGen->doFooter();
        // display web page
        echo $pageGen->fetchHTML();
    }
    catch(Exception $e){
        echo $e->getMessage();
        exit();
    }

    As you can see in the above example, I passed a simple test string (not a “HTMLElement” object) in to the web page generator class, which will result in an exception thrown by the “addHTMLElement()” method, being caught for the appropriate “catch” block, as follows:

    Invalid (X)HTML element

    At this point, I used the “instanceof” operator, in order to determine the validity of input objects, which transform the above web page generator class into a much more efficient piece of code. I hope you realize the vital importance of filtering the input of your class methods by this operator, thus they can be shielded from incorrect data coming from outside.

    Having illustrated the proper implementation of the “instanceof” operator within the web page generator class, there’s still one more thing to be done. Similar to the (X)HTML widget classes I wrote for PHP 4 in my previous article, I’d like to include this operator as part of their “getHTML()” method, in this way allowing the creation of web pages that render nested (X)HTML elements. Thus, let’s jump together into the next section, to see how this is done.



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

       

    PHP ARTICLES

    - 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
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT