php的閉包函式bingto php的閉包函式

2021-10-16 19:16:53 字數 2765 閱讀 5526

[toc]

## 1 閉包(匿名)函式的意義

**閉包(匿名)函式通常作為簡單函式功能的實現。**

閉包(匿名)函式可以**賦值給變數**,或者**作為引數使用**。

閉包(匿名)函式是**函式程式設計**的基礎

## 2 閉包(匿名)函式的使用

### 2-1 匿名函式賦值給變數

$greet = function( $name )

printf ( "hello %s\r\n" , $name );

$greet ( 'world' );

$greet ( 'php' );

### 2-2 匿名函式用作函式引數

echo preg_replace_callback (

'~-([a-z])~' ,

function ( $match ) ;

$ob1 = new a ( 1 );

$ob2 = new a ( 2 );

$cl = $ob1 -> getclosure ();

echo $cl (), "\n" ;

$cl = $cl -> bindto ( $ob2 );

echo $cl (), "\n" ;

輸出:### 4-2 閉包類方法: closure::bind

`public static closure closure::bind ( closure $closure , object $newthis [, mixed $newscope = 'static' ] )`

> $closure:需要修改的匿名函式物件

> $newthis:匿名函式的引數物件

> $newscope:匿名函式的引數類作用域

class a {

private static $sfoo = 1 ;

private $ifoo = 2 ;

$cl1 = static function() {

return a :: $sfoo ;

$cl2 = function() {

return $this -> ifoo ;

$bcl1 = closure :: bind ( $cl1 , null , 'a' );

$bcl2 = closure :: bind ( $cl2 , new a (), 'a' );

echo $bcl1 (), "\n" ;

echo $bcl2 (), "\n" ;

以上例程的輸出類似於:

>[info] 兩種不同在於乙個是物件方法,乙個是類靜態方法

## 5 閉包函式的反射呼叫

閉包函式物件可以作為普通物件,使用反射api進行操作

如think\route.php的route::checkdomain()

if ($rule instanceof \closure) {

$reflect = new \reflectionfunction($rule);

self::$bind = $reflect->invokeargs();

return;

## 6 閉包函式的引數操作

func_num_args() 獲取引數個數

func_get_arg() 獲取特定引數

func_get_args() 獲取引數陣列

類似於js的arguments用法

## 7 閉包函式的使用例項

### 7-1 類中使用閉包函式

class cart

const price_butter = 1.00 ;

const price_milk = 3.00 ;

const price_eggs = 6.95 ;

protected $products = array();

public function add ( $product , $quantity )

$this -> products [ $product ] = $quantity ;

public function getquantity ( $product )

return isset( $this -> products [ $product ]) ? $this -> products [ $product ] :

false ;

public function gettotal ( $tax )

$total = 0.00 ;

$callback =

function ( $quantity , $product ) use ( $tax , & $total )

$priceperitem = constant ( __class__ . "::price_" .

strtoupper ( $product ));

$total += ( $priceperitem * $quantity ) * ( $tax + 1.0 );

array_walk ( $this -> products , $callback );

return round ( $total , 2 );;

$my_cart = new cart ;

$my_cart -> add ( 'butter' , 1 );

$my_cart -> add ( 'milk' , 3 );

$my_cart -> add ( 'eggs' , 6 );

print $my_cart -> gettotal ( 0.05 ) . "\n" ;

## 8 函式程式設計高階

## 9 php的閉包函式與js閉包函式比較

PHP函式閉包

php的閉包函式和js的閉包是一樣的道理,都是函式內部的函式,同樣的閉包會儲存函式內的變數,以方便下次的使用。但是也會有執行次數越多,占用記憶體越多,造成記憶體洩漏的現象。接下來我們舉個例子來說明一下php的閉包,如下 例1 function getfunc print r array return...

PHP 閉包函式

php v5.3閉包函式,閉包函式沒有函式名稱,直接在function 傳入變數即可 使用時將定義的變數當作函式來處理 匿名函式也叫閉包函式 closures允許建立乙個沒有指定沒成的函式,最經常用作 函式引數的值。閉包函式沒有函式名稱,直接在function 傳入變數即可 使用時將定義的變數當作函...

PHP 的閉包 預定函式

在php中,由於存在函式內部不能訪問全域性作用的,所以就需要一種可以引入上一級作用域的語法結構,這種就是 閉包 提到閉包就不得不想起匿名函式,也叫閉包函式 closures 貌似php閉包實現主要就是靠它。宣告乙個匿名函式是這樣 func function 帶結束符 可以看到,匿名函式因為沒有名字,...