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 )

The Object (compound) Type in PHP

use() in PHP

Exception in module wampmanager.exe at 000F15A0 in Windows 8

parent:: AND self:: in PHP

Function to return number of digits of an integer in PHP

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

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

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

Retrieve multiple rows from mysql and automatically create a table in PHP

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

Function to convert strings to strict booleans in PHP

Malware: global $ob_starting;

Latest Articles (in PHP)