
日期:2006-09-28 作者:喜騰小二 來源:PHPChina
三、
使用"instanceof"運運算元
如妳所見,"instanceof"運運算元的使用非常簡單,它用兩個參數來完成其功能。第一個參數是妳想要檢查的物件,第二個參數是類名(事實上是一個介麵名),用於確定是否這個物件是相應類的一個實例。當然,我故意使用了上麵的術語,這樣妳就可以看到這個運運算元的使用是多麼直觀。它的基本語法如下:
| if (object instanceof class name){ //做一些有用的事情 } |
| 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; } } |
| try{ //生成一些HTML元素 $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'; //實例化页面生成器類 $pageGen=new Page生成器(); $pageGen->doHeader(); //新增'HTMLElement'物件 $pageGen->addHTMLElement($teststr) //把簡單的字串傳遞到這個方法 $pageGen->addHTMLElement($h1); $pageGen->addHTMLElement($div); $pageGen->addHTMLElement($par); $pageGen->doFooter(); //顯示網頁 echo $pageGen->fetchHTML(); } catch(Exception $e){ echo $e->getMessage(); exit(); } |
| Invalid (X)HTML element |