php的instanceof和判斷閉包Closure操作示例
本文實(shí)例講述了php的instanceof和判斷閉包Closure。分享給大家供大家參考,具體如下:
類型運(yùn)算符
instanceof 用于確定一個(gè) PHP 變量是否屬于某一類 class 的實(shí)例,在此之前用 is_a(),但是后來(lái) is_a() 被廢棄
<?php class MyClass { } class NotMyClass { } $a = new MyClass; var_dump($a instanceof MyClass); var_dump($a instanceof NotMyClass); ?>
以上例程會(huì)輸出:
bool(true)
bool(false)
instanceof 也可用來(lái)確定一個(gè)變量是不是繼承自某一父類的子類的實(shí)例:
Example #2 對(duì)繼承類使用 instanceof
<?php class ParentClass { } class MyClass extends ParentClass { } $a = new MyClass; var_dump($a instanceof MyClass); var_dump($a instanceof ParentClass); ?>
以上例程會(huì)輸出:
bool(true)
bool(true)
Closure 類
用于代表 匿名函數(shù) 的類.
匿名函數(shù)(在 PHP 5.3 中被引入)會(huì)產(chǎn)生這個(gè)類型的對(duì)象。在過去,這個(gè)類被認(rèn)為是一個(gè)實(shí)現(xiàn)細(xì)節(jié),但現(xiàn)在可以依賴它做一些事情。自 PHP 5.4 起,這個(gè)類帶有一些方法,允許在匿名函數(shù)創(chuàng)建后對(duì)其進(jìn)行更多的控制。
除了此處列出的方法,還有一個(gè) __invoke 方法。這是為了與其他實(shí)現(xiàn)了 __invoke()魔術(shù)方法 的對(duì)象保持一致性,但調(diào)用匿名函數(shù)的過程與它無(wú)關(guān)。
類摘要
Closure { /* 方法 */ __construct ( void ) public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] ) public Closure bindTo ( object $newthis [, mixed $newscope = 'static' ] ) }
Table of Contents
- Closure::__construct — 用于禁止實(shí)例化的構(gòu)造函數(shù)
- Closure::bind — 復(fù)制一個(gè)閉包,綁定指定的$this對(duì)象和類作用域。
- Closure::bindTo — 復(fù)制當(dāng)前閉包對(duì)象,綁定指定的$this對(duì)象和類作用域。
判斷是不是閉包
if ( $this->{$method} instanceof Closure ) { return call_user_func_array($this->{$method},$args); } else { throw new Exception("Invalid Function"); } //一切都要自行測(cè)試 if ( $class instanceof Closure ) { } else { }
參考:
http://php.net/manual/zh/language.operators.type.php
http://php.net/manual/zh/class.closure.php
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP基本語(yǔ)法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章
php實(shí)現(xiàn)微信公眾號(hào)主動(dòng)推送消息
這篇文章主要介紹了php實(shí)現(xiàn)微信公眾號(hào)主動(dòng)推送消息的方法,PHP版微信公共平臺(tái)消息主動(dòng)推送,突破訂閱號(hào)一天只能發(fā)送一條信息限制,需要的朋友可以參考下2015-12-12【CLI】利用Curl下載文件實(shí)時(shí)進(jìn)度條顯示的實(shí)現(xiàn)
這篇文章主要給大家介紹了關(guān)于【CLI】利用Curl下載文件實(shí)時(shí)進(jìn)度條顯示的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2018-03-03一個(gè)基于PDO的數(shù)據(jù)庫(kù)操作類(新) 一個(gè)PDO事務(wù)實(shí)例
原先已經(jīng)寫過一個(gè)PDO的數(shù)據(jù)庫(kù)操作類,這次只是在原先基礎(chǔ)上進(jìn)行修改。2011-07-07php 實(shí)現(xiàn)進(jìn)制相互轉(zhuǎn)換
最近的項(xiàng)目中需要用到進(jìn)制轉(zhuǎn)換,這個(gè)問題在剛剛接觸計(jì)算機(jī)理論時(shí)候,還是很會(huì)的,好久不用,居然模糊了……2016-04-04