php-lambda-5.2

A small function for providing closure-like capabilities in PHP 5.2

  • 所有者: lokothodida/php-lambda-5.2
  • 平台:
  • 許可證: MIT License
  • 分類:
  • 主題:
  • 喜歡:
    0
      比較:

Github星跟蹤圖

PHP Closures/Lambdas for 5.2

A small experiment to providing closure-like capabilities in PHP 5.2. This is
a limited project and is only intended as a small polyfill-like solution for
those with PHP hosts that still do not provide 5.3+ and would like some of the
benefits of 5.3+'s closures (namely variable importing).

Note: this solution currently does not pass the imported variables by
reference.

Initialization

Either load the global lambda function from this project:

// Defines global function 'lambda'
// Usage: lambda($params);
include 'lambda-global.php';

Or load the local version into a variable:

// Defines local function $lambda
// Usage: $lambda($params);
$lambda = include 'lambda-local.php';

Syntax

$lambda(array(
  'args' => array(/* */),  // Arguments for the new function
  'use'  => array(/* */),  // Variables to import into the scope of the function
  'fn'   => /* */,         // Body of the function
));

Examples

Basic usage

// Define some variables
$x = 3;
$y = 4;

// Create a closure that uses $x and $y
$myClosure = $lambda(array(
  'args' => array('$z'),
  'use'  => array('$x' => $x, '$y' => $y),
  'fn'   => 'return $z * $y * $z;'
));

$myClosure(5); // 60

External files

example.php

// Define some variables
$x = 3;
$y = 4;

// Create a closure that uses $x and $y
$myClosure = $lambda(array(
  'args' => array('$z'),
  'use'  => array('$x' => $x, '$y' => $y),
  'fn'   => 'myclosure.php'
));

$myClosure(5); // 60

myclosure.php

<?php
// Having a separate file allows you to define the function without building
// your own unweildly string in the 'fn' argument
return $z * $y * $z;

Shorthands

// If $params[0] exists but not $params['fn'], $params['fn'] will take
// $params[0]'s value:
$callback = $lambda(array('use' => array('$stuff' => 3), '
  var_dump($stuff);
'));

$callback(); // 3


主要指標

概覽
名稱與所有者lokothodida/php-lambda-5.2
主編程語言PHP
編程語言PHP (語言數: 1)
平台
許可證MIT License
所有者活动
創建於2015-08-07 19:50:02
推送於2015-08-07 21:22:30
最后一次提交2015-08-07 22:21:58
發布數0
用户参与
星數2
關注者數1
派生數0
提交數5
已啟用問題?
問題數0
打開的問題數0
拉請求數0
打開的拉請求數0
關閉的拉請求數0
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?