国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊(cè) PHP強(qiáng)制對(duì)象類型之instanceof操作符

PHP強(qiáng)制對(duì)象類型之instanceof操作符

Jun 21, 2016 am 09:11 AM
attributes function output this

對(duì)象

一、簡(jiǎn)介

  在PHP中實(shí)現(xiàn)強(qiáng)制對(duì)象類型有時(shí)可能非常重要。如果缺少了它,或是因?yàn)槿狈@方面的知識(shí)——基于不正確的編程假設(shè),或者僅僅是由于懶惰,那么你會(huì)在特定的Web應(yīng)用程序中看到你所不希望的結(jié)果。特別是當(dāng)用PHP 4進(jìn)行編程時(shí),使用"is_a()"函數(shù)(盡管還有其它方法)來驗(yàn)證你所使用的對(duì)象的類型是非常容易的事情。毫無疑問,強(qiáng)制對(duì)象類型還可以被用于過濾輸入對(duì)象(需要被作為參數(shù)傳遞到同一個(gè)應(yīng)用程序中的其它PHP類)。

  不過,PHP 4并沒有暴露一些有關(guān)于它的對(duì)象模型的弱點(diǎn)-為了實(shí)現(xiàn)某些在成熟的面向?qū)ο蟮恼Z言中出現(xiàn)的特征,它偶而可能要求編寫另外的代碼。長(zhǎng)時(shí)間以來,這一事實(shí)已經(jīng)為PHP社區(qū)眾所周知。然而,隨著PHP 5的發(fā)行,許多這些極有價(jià)值的特征作為改進(jìn)的對(duì)象模型的一部分被添加到其中。它們將有助于更為緊密地實(shí)現(xiàn)基于對(duì)象的代碼的開發(fā)-允許你使用特定的對(duì)象特征。

  在上面的情況下,當(dāng)涉及到對(duì)象類型強(qiáng)制時(shí)應(yīng)該特別注意。實(shí)際上,在一個(gè)Web應(yīng)用程序的執(zhí)行期間,PHP 5提供給開發(fā)者至少兩種方法來檢查對(duì)象類型——它們分別是“instanceof”操作符和“類型提示”特征?,F(xiàn)在轉(zhuǎn)到本文的主題,我將介紹PHP 5中"instanceof"操作符的使用;你很快就會(huì)發(fā)現(xiàn),它可以非常方便地用來確定是否你正在使用的對(duì)象屬于一個(gè)特定的類型。

  本文將通過一些面向?qū)ο蟮氖纠齺韼椭憷斫馊绾卧赑HP 5中實(shí)現(xiàn)強(qiáng)制對(duì)象類型。

  二、 你不該做什么

  為了展示在PHP 5中如何實(shí)現(xiàn)對(duì)象類型強(qiáng)制,我將使用(X)HTML widget類,還有一個(gè)簡(jiǎn)單的頁面生成器類,并作了簡(jiǎn)單的修改以適合PHP 5開發(fā)環(huán)境。

  我的第一個(gè)示例列舉了一些派生自一個(gè)抽象的基類"HTMLElement"的(X)HTML widget類,它跳過了到它們的輸入對(duì)象類型的檢查。請(qǐng)先看下面的類:

//定義抽象類'HTMLElement'
abstract class HTMLElement{
 protected $attributes;
 protected function __construct($attributes){
  if(!is_array($attributes)){
   throw new Exception('Invalid attribute type');
  }
  $this->attributes=$attributes;
 }
 // 抽象的'getHTML()'方法
 abstract protected function getHTML();
}
//定義具體的類'Div'-擴(kuò)展HTMLElement
class Div extends HTMLElement{
 private $output='<div ';
 private $data;
 public function __construct($attributes=array(),$data){
  parent::__construct($attributes);
  $this->data=$data;
 }
 //'getHTML()'方法的具體實(shí)現(xiàn)
 public function getHTML(){
  foreach($this->attributes as $attribute=>$value){
   $this->output.=$attribute.'="'.$value.'" ';
  }
  $this->output=substr_replace($this->output,'>',-1);
  $this->output.=$this->data.'</div>';
  return $this->output;
 }
}
//定義具體類'Header1'-擴(kuò)展HTMLElement
class Header1 extends HTMLElement{
 private $output='<h1 ';
 private $data;
 public function __construct($attributes=array(),$data){
  parent::__construct($attributes);
  $this->data=$data;
 }
 //'getHTML()'方法的具體的實(shí)現(xiàn)
 public function getHTML(){
  foreach($this->attributes as $attribute=>$value){
   $this->output.=$attribute.'="'.$value.'" ';
  }
  $this->output=substr_replace($this->output,'>',-1);
  $this->output.=$this->data.'</h1>';
  return $this->output;
 }
}
//定義具體類'Paragraph'-擴(kuò)展HTMLElement
class Paragraph extends HTMLElement{
 private $output='<p ';
 private $data;
 public function __construct($attributes=array(),$data){
  parent::__construct($attributes);
  $this->data=$data;
 }
 //'getHTML()'方法的具體實(shí)現(xiàn)
 public function getHTML(){
  foreach($this->attributes as $attribute=>$value){
  $this->output.=$attribute.'="'.$value.'" ';
 }
 $this->output=substr_replace($this->output,'>',-1);
 $this->output.=$this->data.'</p>';
 return $this->output;
}
}
//定義具體類'UnorderedList'-擴(kuò)展HTMLElement
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()'方法的具體實(shí)現(xiàn)
 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.='<li>'.$item.'</li>';
  } 
  $this->output.='</ul>';
  return $this->output;
 }
}
  如你所見,上面的(X)HTML widget類在生成一個(gè)網(wǎng)面中特定的元素時(shí)是非常有用的,但是我有意地把每一個(gè)類的代碼寫成這樣,這樣它們就不能夠驗(yàn)證輸入?yún)?shù)的有效性。你可能已經(jīng)想到,輸入?yún)?shù)將直接被傳遞到類構(gòu)造器中并且作為屬性賦值。問題出現(xiàn)了:這樣做有什么錯(cuò)誤嗎?是的,有?,F(xiàn)在,我將定義我的最簡(jiǎn)單的頁面生成器類,并且用這樣一些widget來填充(feed)它,這樣你就可以看到這個(gè)類的輸入是如何與不正確的對(duì)象相混雜。下面是該頁面生成器類的簽名:

class PageGenerator{
 private $output='';
 private $title;
 public function __construct($title='Default Page'){
  $this->title=$title;
 }
 public function doHeader(){
  $this->output='<html><head><title>'.$this-
 ?。総itle.'</title></head><body>';
 }
 public function addHTMLElement($htmlElement){
  $this->output.=$htmlElement->getHTML();
 }
 public function doFooter(){
  $this->output.='</body></html>';
 }
 public function fetchHTML(){
  return $this->output;
 }
}
  現(xiàn)在,我們開始實(shí)例化一些(X)HTML widget對(duì)象,并且把它們傳遞到相應(yīng)的生成器類,如下面的示例所示:

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');
 $ul=new UnorderedList(array ('name'=>'list1','class'=>'listclass'),array
('item1'=>'value1','item2'=>'value2','item3'=>'value3'));
//實(shí)例化頁面生成器類
 $pageGen=new Page生成器();
 $pageGen->doHeader();
 // 添加'HTMLElement'對(duì)象
 $pageGen->addHTMLElement($h1);
 $pageGen->addHTMLElement($div);
 $pageGen->addHTMLElement($par);
 $pageGen->addHTMLElement($ul);
 $pageGen->doFooter();
 //顯示網(wǎng)面
 echo $pageGen->fetchHTML();
}
catch(Exception $e){
 echo $e->getMessage();
 exit();
}
  在運(yùn)行上面的PHP代碼后,你所得到的結(jié)果是一個(gè)簡(jiǎn)單的網(wǎng)頁-它包含一些前面創(chuàng)建的(X)HTML對(duì)象。這種情況下,如果因某些原因該網(wǎng)頁生成器類收到一個(gè)不正確的對(duì)象并調(diào)用它的"addHTML()"方法,那么你很容易理解將會(huì)發(fā)生的事情。在此,我重新修改了這里的沖突條件-通過使用一個(gè)不存在的(X)HTML widget對(duì)象。請(qǐng)?jiān)俅慰匆幌孪旅娴拇a:

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');
 $ul=new UnorderedList(array ('name'=>'list1','class'=>'listclass'),array
('item1'=>'value1','item2'=>'value2','item3'=>'value3'));
 //實(shí)例化頁面生成器類
 $pageGen=new Page生成器();
 $pageGen->doHeader();
 //添加'HTMLElement'對(duì)象
 $pageGen->addHTMLElement($fakeobj) //把并不存在的對(duì)象傳遞
到這個(gè)方法
 $pageGen->addHTMLElement($div);
 $pageGen->addHTMLElement($par);
 $pageGen->addHTMLElement($ul);
 $pageGen->doFooter();
 // 顯示網(wǎng)面
 echo $pageGen->fetchHTML();
}
catch(Exception $e){
 echo $e->getMessage();
 exit();
}
  在這種情況中,如下面一行所顯示的:

$pageGen->addHTMLElement($fakeobj)//把不存在的對(duì)象傳遞到這個(gè)方法
  一個(gè)并不存在的(X)HTML widget對(duì)象被傳遞到該頁面生成器類,這樣會(huì)導(dǎo)致一個(gè)致命性錯(cuò)誤:

Fatal error: Call to a member function on a non-object in
path/to/file


  怎么樣?這就是對(duì)傳遞到生成器類的對(duì)象的類型不進(jìn)行檢查的直接懲罰!因此在編寫你的腳本時(shí)一定要記住這個(gè)問題。幸好,還有一個(gè)簡(jiǎn)單的方案來解決這些問題,而且這也正是"instanceof"操作符的威力所在。如果你想要看一下這個(gè)操作符是如何使用的,請(qǐng)繼續(xù)往下讀吧。

[1]?[2]?下一頁??



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

How to use Attributes to manage code annotations in PHP8? How to use Attributes to manage code annotations in PHP8? Oct 18, 2023 am 09:48 AM

How to use Attributes to manage code annotations in PHP8? With the release of PHP8, an exciting new feature was introduced, namely Attributes. Attributes is a method of code annotation that allows us to add metadata to classes, methods, and attributes in a structured way. In this article, we will explore how to use Attributes to manage code annotations in PHP8 and provide some specific code examples. 1. What is Attrib?

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

Detailed explanation of the role and function of the MySQL.proc table Detailed explanation of the role and function of the MySQL.proc table Mar 16, 2024 am 09:03 AM

Detailed explanation of the role and function of the MySQL.proc table. MySQL is a popular relational database management system. When developers use MySQL, they often involve the creation and management of stored procedures (StoredProcedure). The MySQL.proc table is a very important system table. It stores information related to all stored procedures in the database, including the name, definition, parameters, etc. of the stored procedures. In this article, we will explain in detail the role and functionality of the MySQL.proc table

Let's talk about why Vue2 can access properties in various options through this Let's talk about why Vue2 can access properties in various options through this Dec 08, 2022 pm 08:22 PM

This article will help you interpret the vue source code and introduce why you can use this to access properties in various options in Vue2. I hope it will be helpful to everyone!

How to use Attributes to add custom annotations to classes in PHP8? How to use Attributes to add custom annotations to classes in PHP8? Oct 18, 2023 am 10:16 AM

How to use Attributes to add custom annotations to classes in PHP8? Custom annotations are a way to add metadata to a class or method, which can help us obtain and process additional information on a specific class or method at runtime. In PHP8, the concept of Attributes was introduced, which allows us to easily add custom annotations to classes. This article will introduce how to use Attributes to implement custom annotations for classes in PHP8 and provide specific code examples. In PHP8, since

PHP output GD image to browser or file PHP output GD image to browser or file Mar 21, 2024 am 10:41 AM

This article will explain in detail how PHP outputs GD images to a browser or file. I think it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP outputs GD images to a browser or file Introduction The phpGD library provides powerful functions for processing images, allowing you to create, edit and output images. Images can be output to a browser or file for display or further processing. Output to Browser To output an image to a browser, use the following steps: Create an image resource: Use the imagecreate() function to create an image resource. Load image data: use imagepng(), imagejpeg() or imagegif()

How to use SOA functions in PHP How to use SOA functions in PHP May 18, 2023 pm 01:10 PM

With the development of the Internet, SOA (service-oriented architecture) has become an important technical architecture in today's enterprise-level systems. Services in the SOA architecture can be reused, reorganized and extended, while also simplifying the system development and maintenance process. As a widely used Web programming language, PHP also provides some function libraries for implementing SOA. Next, we will detail how to use SOA functions in PHP. 1. The basic concept of SOA. SOA is a distributed system development idea and architecture.

See all articles