登录  /  注册

php类型运算符"instanceof"操作符的扩展使用

伊谢尔伦
发布: 2017-06-21 16:11:21
原创
1231人浏览过

"instanceof"操作符在被直接注入到页面生成器类的输入对象进行类型检查方面所表现出的良好功能。现在,再进一步来把一个检查例程添加到(x)html widget类的构造器和"gethtml()"方法中,这样它们可以接受其它的widget作为输入参数。请检查下面改进的类:

class Div extends HTMLElement{
 private $output='<div ';
 private $data;
 public function construct($attributes=array(),$data){
  if(!$data instanceof HTMLElement&&!is_string($data)){
   throw new Exception('Invalid parameter type');
  }
  parent::construct($attributes);
  $this->data=$data;
 }
 //'getHTML()'方法的具体实现
 public function getHTML(){
  foreach($this->attributes as $attribute=>$value){
   $this->output.=$attribute.'="'.$value.'" ';
  }
  $this->output=substr_replace($this->output,'>',-1);
  $this->output.=($this->data instanceof HTMLElement)?
  $this->data->getHTML():$this->data;
  $this->output.='</div>';
  return $this->output;
 }
}
class Header1 extends HTMLElement{
 private $output='<h1 ';
 private $data;
 public function construct($attributes=array(),$data){
  if(!$data instanceof HTMLElement&&!is_string($data)){
   throw new Exception('Invalid parameter type');
  }
  parent::construct($attributes);
  $this->data=$data;
 }
 //'getHTML()'方法的具体实现
 public function getHTML(){
  foreach($this->attributes as $attribute=>$value){
   $this->output.=$attribute.'="'.$value.'" ';
  }
  $this->output=substr_replace($this->output,'>',-1);
  $this->output.=($this->data instanceof HTMLElement)?
  $this->data->getHTML():$this->data;
  $this->output.='</h1>';
  return $this->output;
 }
}
class Paragraph extends HTMLElement{
 private $output='<p ';
 private $data;
 public function construct($attributes=array(),$data){
  if(!$data instanceof HTMLElement&&!is_string($data)){
   throw new Exception('Invalid parameter type');
  }
  parent::construct($attributes);
  $this->data=$data;
 }
 //'getHTML()'方法的具体实现
 public function getHTML(){
  foreach($this->attributes as $attribute=>$value){
   $this->output.=$attribute.'="'.$value.'" ';
  }
  $this->output=substr_replace($this->output,'>',-1);
  $this->output.=($this->data instanceof HTMLElement)?
  $this->data->getHTML():$this->data;
  $this->output.='</p>';
  return $this->output;
 }
}
class UnorderedList extends HTMLElement{
 private $output='<ul ';
 private $items=array();
 public function construct($attributes=array(),$items=array()){
  parent::construct($attributes);
  if(!is_array($items)){
   throw new Exception('Invalid parameter for list items');
 }
 $this->items=$items;
}
//'getHTML()'方法的具体实现
public function getHTML(){
 foreach($this->attributes as $attribute=>$value){
  $this->output.=$attribute.'="'.$value.'" ';
 }
 $this->output=substr_replace($this->output,'>',-1);
 foreach($this->items as $item){
  $this->output.=($item instanceof
  HTMLElement)?'<li>'.$item->getHTML().'</li>':'<li>'.$item.'</li>';
 }
 $this->output.='</ul>';
 return $this->output;
}
}
登录后复制

 如上面的类所展示的,为了允许在生成相应的网页时实现嵌套的(X)HTML元素,分别重构了它们的构造器和"getHTML()"方法。请注意,在每一个类的构造器中包含了下面的条件块:

if(!$data instanceof HTMLElement&&!is_string($data)){
throw new Exception('Invalid parameter type');
}
登录后复制

  至此,实际做的是确保仅有字符串数据和"HTMLElement"类型对象允许作为每一个类的输入参数。否则,将分别由各自方法抛出一个异常,并且有可能导致应用程序的停止执行。所以,这就是对输入数据的检查过程。现在,让我们看一下"getHTML()"方法的新的签名,其中也使用了"instanceof"操作符:

$this->output.=($this->data instanceof HTMLElement)?$this->data-
>getHTML():$this->data;
登录后复制

 如你所见,在这种情况下,对于利用(X)HTML widget类的多态性特征方面this操作符是非常有用的。如果$data属性也是一个widget,那么它的"getHTML()"方法将被正确调用,这会导致显示嵌套的网页元素。另一方面,如果它仅是一个字符串,那么它就被直接添加到当前类的所有输出上。

  至此,为了确保某些对象属于一个特定的类型,你可能已经理解了php 5中"instanceof"操作符的用法。正如你在本文中所见,在PHP 5中强制对象类型其实是一个相当直接的工作。现在,你最好开发一个使用这个方法来过滤你的PHP应用程序中的对象的例子来加深自己的理解。

<?php
//定义一个抽像类HTMLElement
abstract class HTMLElement
{
    protected  $attributes;
    protected  function construct($_attributes)
    {
        if(!is_array($_attributes))
        {
           throw new Exception("attributes not is array"); 
        }
        $this->attributes = $_attributes;
    }
    //定义一个虚函数
    abstract function getHTML();
}
 
 
//定义具体的类"Div"扩展HTMLElement
class Div extends HTMLElement
{
    private $_output = "<div";
    private $_data;
    public function construct($_attributes=array(), $data)
    {
        //扩展"instanceof"操作符的使用:嵌套(X)HTML widget
        if(!$data instanceof HTMLElement && !is_string($data)) {
            throw new Exception("data type error");
        }      
        parent::construct($_attributes);
        $this->_data = $data;
    }
    public function getHTML()
    {
        foreach ($this->attributes as $key=>$val)
        {
             $this->_output.=  " ".$key."=&#39;".$val."&#39; ";
        }
        $this->_output =substr_replace($this->_output,">",-1);
        $this->_output .= $this->_data instanceof HTMLElement ? $this->_data->getHTML()."</div>" : $this->_data."</div>";
        return $this->_output;
    }
}
 
//定义具体的类"H1"扩展
class h1 extends HTMLElement
{
    private $_output="<h1";
    private $_data;
    public function construct($_attributes=array(), $data)
    {
        parent::construct($_attributes);
        $this->_data = $data;
    }
     
    public function getHTML()
    {
        foreach($this->attributes as $key=>$val)
        {
            $this->_output.=  " ".$key."=&#39;".$val."&#39; ";
        }
        $this->_output = substr_replace($this->_output, ">", -1);
        $this->_output .= $this->_data."<h1>";
        return $this->_output;
    }
}
 
//定义具体的类"ul"
class ul extends HTMLElement
{
    public $output = "<ul";
    private $ulitem=array();
    public function construct($_attributes=array(), $_ulitem=array())
    {  
        parent::construct($_attributes);
        $this->ulitem = $_ulitem;
    }
     
    public function getHTML()
    {
        foreach($this->attributes as $key=>$val)
        {
            $this->_output.=  " ".$key."=&#39;".$val."&#39; ";
        }
        $this->output = substr_replace($this->output, ">",-1);
        foreach($this->ulitem as $ukey=>$uval){
            $this->output .="<li>".$uval."</li>";
        }
        $this->output.="</ul>";
        return $this->output;       
    }
}
 
 
//生成页面的类
class PageGenerator
{
    private $_output;
    private $_title;
    public function construct($title=" Default page")
    {
        $this->_title = $title;
    }
     
    public function doHead()
    {
        $this->_output.="<html><head><title>".$this->_title."</title></head><body>";
    }
     
//  public function addHTMLElement($HTMLElement)
//  {
//      $this->_output.= $HTMLElement->getHTML();
//  }
    //对addHTMLElement进行改进
    //可以保证传入的不是HTMLElement类对像直接报错
    public function addHTMLElement($HTMLElement)
    {
         if(!$HTMLElement instanceof HTMLElement)
         {
            throw new Exception(&#39;Invalid (X)HTML element&#39;);
         }
         $this->_output.= $HTMLElement->getHTML();
    }
 
    public function doFooter()
    {
        $this->_output.="</body></html>";
    }
     
    public function fetchHTML()
    {
        return $this->_output;
    }
}
 
try{   
    $attribute = array("class"=>"className", "style"=>"color:#000");
    $h1 = new H1($attribute, "h1内容");
    $attribute = array("class"=>"className", "style"=>"color:#000");
    $ul = new ul($attribute, array("li第一行内容","li第二行内容","li第三行内容"));
     
     
    $attribute = array("class"=>"className", "style"=>"color:red");
    $div = new Div($attribute, $ul);
    $page = new PageGenerator();
//  $str="我是个字符串";
//  $page->addHTMLElement($str);
    $page->addHTMLElement($h1);
    $page->addHTMLElement($div);
    //  $page->addHTMLElement($ul);
    echo $page->fetchHTML();    
}
catch(Exception $e){
    echo $e->getMessage();
    die();
}
?>
登录后复制

以上就是php类型运算符"instanceof"操作符的扩展使用的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号