Categories
PHP Programming

PHP instanceof to determine what kind of object we are dealing with

Example:

class ShopProductWriter {
    public function write( $shopProduct ) {
        if ( ! ( $shopProduct instanceof CdProduct )  &&
             ! ( $shopProduct instanceof BookProduct ) ) {
            die( "wrong type supplied" );
        }
         $str  = "{$shopProduct->title}: " .
                $shopProduct->getProducer() .
                " ({$shopProduct->price})n";
        print $str;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *