PHP
  Home arrow PHP arrow Page 3 - Enforcing Object Types in PHP: Using t...
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

Enforcing Object Types in PHP: Using the PHP5 instanceof Operator
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 6
    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:
      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


    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


       · With reference to filtering input objects in PHP, this second article of the series...
     

       

    PHP ARTICLES

    - 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
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





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