Home arrow PHP arrow Page 3 - Enforcing Object Types in PHP: Using the PHP5 instanceof Operator

Forcing object types in PHP 5: using the “instanceof” operator - PHP

This is the second installment of the series “Enforcing object types in PHP.” Welcome back. As you’ll surely know, this three-part series goes through the basic concepts of object type enforcement in PHP 4/PHP 5. It explores different approaches for checking types of objects to help you avoid possible code contamination when objects of incorrect type are inputted within PHP classes.

TABLE OF CONTENTS:
  1. Enforcing Object Types in PHP: Using the PHP5 instanceof Operator
  2. Checking object types in PHP 5: what you shouldn’t do
  3. Forcing object types in PHP 5: using the “instanceof” operator
  4. Extending the use of the “instanceof” operator: nesting (X)HTML widgets
By: Alejandro Gervasio
Rating: starstarstarstarstar / 10
February 22, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: