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?
已存档?
是复刻?
已锁定?
是镜像?
是私有?