匿名函式,也叫閉包函式(closures) ,允許臨時創建一個沒有制定名稱的函式,最常用作回呼函式(callback)引數的值,
閉包函式也可以作為變數的值來使用,PHP將會自動把此種運算式轉換成內置類 Closure 的物件實體,把一個 Closure 物件賦值給一個變數的方式與普通變數賦值的語法一樣,最后也要加上分號,
匿名函式變數賦值實體:
<?php
$printString = function($arg){
echo $arg;
};
$printString('hello world');
//輸出 hello world
閉包函式繼承父作用域中的變數,任何此類變數都應該用 use 語言結構傳遞進去,
從父作用域繼承變數:
<?php
//定義變數
$message = 'hello world';
//匿名函式變數賦值
$example = function(){
var_dump($message);
};
//執行后輸出 Notice: Undefined variable
$example();
在未使用關鍵字use 時,PHP不能在匿名函式中呼叫所在代碼背景關系變數,
<?php
//定義變數
$message = 'hello';
//匿名函式繼承父作用域的變數($message)
$example = function() use ($message){
var_dump($message);
};
//輸出 string 'hello' (length=5)
echo $example();
//同樣輸出 string 'hello' (length=5)
$message = 'world';
echo $example();
使用關鍵字use時,PHP可以在呼叫匿名函式中呼叫所在代碼背景關系的變數,但為什么第二次呼叫沒有發生變化哪?
是因為匿名函式可以保存所在代碼塊背景關系的一些變數和值(即:閉包函式將會保存第一次繼承的父作用域的變數和值),值傳遞只是傳遞繼承父作用域中變數和值的一個副本,
要想改變父作用域的值并體現在匿名函式呼叫中,該怎么辦哪?
我們要用參考傳遞(即:在變數前面添加&),如下所示:
<?php
//定義變數
$message = 'hello';
//匿名函式繼承父作用域的變數($message)
$example = function() use (&$message){
var_dump($message);
};
//輸出 string 'hello' (length=5)
echo $example();
//輸出 string 'world' (length=5)
$message = 'world';
echo $example();
同樣閉包函式也可以接受常規引數的傳遞,如下所示:
<?php
//定義變數
$message = 'hello';
$message2 = 'hello2';
//匿名函式繼承父作用域的變數($message)
$example = function($arg) use (&$message2, $message){
var_dump($message2 . ' ' . $message . ' ' . $arg);
};
echo $example('world');
$message2 = 'world';
//輸出 string 'hello world' (length=11)
echo $example('world');
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/115605.html
標籤:PHP
上一篇:PHP mysqli_fetch_object MySQLi 函式
下一篇:[Php] windows下使用composer出現SHA384 is not supported by your openssl extension
