[英]PHP 5.3.0 USE identifier
我昨天問了一個關於 USE 標識符的問題,得到了回答PHP 5.3.0 USE 關鍵字——如何在 5.2 中反向移植? .
但是,我不得不擴展我的腳本來執行此操作兩次,並且不確定我如何同時適應這兩者
$available_event_objects = array_filter($event_objects, function ($event_object) use ($week_events) {
// keep if the event is not in $week_events
return !in_array($event_object, $week_events);
});`
和
$calendar_weeks[$week_count][$calendar_date] = array_filter($available_event_objects, function ($event_object) use ($date_pointer) {
// keep if the event is happening on this day
return ($date_pointer >= $event_object->start_date && $date_pointer <= $event_object->end_date);
});`
如何更改它以使其在 5.2.9 中工作?
有人可以指出我正確的方向嗎?
干杯
PHP 在 5.3 之前沒有匿名函數。 您必須改用任何回調類型。 因為這變得更加困難並且對於像您這樣的用例不是很慣用,所以我建議您改用命令式編程風格。
$available_event_objects = array();
foreach ($event_objects as $event_object) {
if (in_array($event_object, $week_events)) {
$available_event_objects[] = $event_object;
}
}
也就是說,對於這種情況,您可以自由使用array_intersect
,即。 $available_event_objects = array_intersect($week_events, $event_objects);
更新的答案:
雖然原始問題中的答案是正確的,並且確實允許您在 php 5.2 中輕松使用 array_filter,而無需關閉; 簡單地做一個 for 循環會更容易:
$output = array_filter($input, function($input) use ($stuff) { return /* condition */ } );
更改為:
$output = array();
foreach($input as $key=>$value) {
if (/* condition */) {
$output[$key] = $value;
}
}
它在手冊http://www.php.net/manual/en/functions.anonymous.php下的“閉包”下被粗略地涵蓋。
use ($var)
的作用是在匿名 function 和父 scope 之間共享一個變量。 通常它只會保留初始值,並將該參數實際上轉換為 static 變量。
要將其轉換為與 PHP 5.2 兼容的構造,最好將閉包轉換為 static 回調函數。 代替= function () {}
寫一個普通的聲明:
function cb_event_filter_week($event_object) {
一個非常不漂亮的方法是通過全局 scope 共享關閉/ use
變量。 為此,將 function 重寫為
function cb_event_filter_week($event_object) {
global $week_events;
您必須在父 function 中執行相同的操作,並對其進行初始化。 並且強烈建議給該變量一個更獨特的名稱,一個更好的選擇是 static 變量:如果您只需要在應用程序流程中的一個點(!)調用此回調 function:
function cb_event_filter_week($event_object) {
static $week_events = 0;
真的取決於它是如何使用的。 但無論哪種情況,您都可以編寫= array_filter($event_objects, "cb_event_filter_week")
在 PHP 5.2 中使用它們
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.