Programming Tutorials

use() in PHP

By: Anonymous in PHP Tutorials on 2011-10-29  

use() parameters are early binding - they use the variable's value at the point where the lambda function is declared, rather than the point where the lambda function is called (late binding).

If you want late binding put & before the variable inside use()

<?php
$fn = function () use (&$var) { echo $var; };
?>

Examples:

<?php
// problem 1: this should echo "Canada", not a php notice
$fn = function () use ($country) { echo $country . "\n"; };
$country = 'Canada';
$fn();
// problem 2: this should echo "Canada", not "UnitedStates"
$country = 'UnitedStates';
$fn = function () use ($country) { echo $country . "\n"; };
$country = 'Canada';
$fn();
// problem 3: this should echo "Canada", not "UnitedStates"
$country = (object)array('name' => 'UnitedStates');
$fn = function () use ($country) { echo $country->name . "\n"; };
$country = (object)array('name' => 'Canada');
$fn();
// problem 4: this outputs "Canada". if this outputs "Canada",
// then so should problem 2 above. otherwise this should be
// just as broken as problem 2 and be outputting "UnitedStates"
$country = (object)array('name' => 'UnitedStates');
$fn = function () use ($country) { echo $country->name . "\n"; };
$country->name = 'Canada';
$fn();
?>





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

use() in PHP

PHP pages does not display in IIS 6 with Windows 2003

Building PHP with Apache2 on SuSE Professional 9.1/9.2

Installing PHP with Apache 2.x on HP UX 11i and configuring PHP with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Installing PHP with nginx-server under windows

Warning: session_start(): open .... failed - PHP error

Convert IP address to integer and back to IP address in PHP

Function to force strict boolean values in PHP

Function to return number of digits of an integer in PHP

Function to sort array by elements and count of element in PHP

Floating point precision in PHP

Latest Articles (in PHP)