php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #49765 Closure: Unreachable static declaration breaks lexical reference
Submitted: 2009-10-04 13:00 UTC Modified: 2017-09-27 14:26 UTC
From: robinf@php.net Assigned: cmb (profile)
Status: Closed Package: Scripting Engine problem
PHP Version: * OS: *
Private report: No CVE-ID: None
 [2009-10-04 13:00 UTC] robinf@php.net
Description:
------------
Hi,

Closures' lexical variable descriptors are stored in the same container as function-scope statics: zend_function.op_array.static_variables.

This can cause unexpected behaviour when the same name is used for a lexical variable and a function-scope static. For example, the testcase below shows how an apparently unreachable function-scope static declaration impacts an assignment to a lexical reference.

This is because static declarations are identified at compile time (regardless of the execution path within the function), and they end up taking precedence over lexical vars.

Reproduce code:
---------------
<?php
$ref = 0;

$closure = function () use (&$ref) {
	var_dump($ref++);
	if (false) { static $ref = 777; }
};

echo "Unreachable static declaration breaks lexical reference:\n";
$closure();     // 777
var_dump($ref); // 0

Expected result:
----------------
Unreachable static declaration breaks lexical reference:
int(0)
int(1)

Actual result:
--------------
Unreachable static declaration breaks lexical reference:
int(777)
int(0)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-10-04 13:03 UTC] robinf@php.net
From an implementation perspective, I can see why using the static_variables container for lexical vars makes sense.

But I think the behaviour above might be too prone to confusion. Perhaps there could be a warning when name clashes are detected, or at least something in the doc?
 [2010-12-20 09:35 UTC] jani@php.net
-Package: Feature/Change Request +Package: Scripting Engine problem -PHP Version: 5.3SVN-2009-10-04 (snap) +PHP Version: *
 [2017-09-27 14:26 UTC] cmb@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: cmb
 [2017-09-27 14:26 UTC] cmb@php.net
This issue has been fixed with 65e456f[1] (PHP 7.1.0).

[1] <http://git.php.net/?p=php-src.git;a=commit;h=65e456f>
 
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Tue Jan 28 09:01:23 2020 UTC