note 20407 modified in language.variables.scope by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 01:43:41 +0000 |
| Subject: | note 20407 modified in language.variables.scope by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155588@lists.php.net to get a copy of this message | ||
Not sure of the implications of this but...
You can create nested functions within functions but you must make sure they aren't defined
twice, e.g.:
<?php
function norm($a, $b) {
static $first_time = true;
if ($first_time) {
function square($x) {
return $x * $x;
}
$first_time = false;
}
return sqrt(square($a) + square($b));
}
print square(5); // error, not defined yet
print norm(5,4);
print "<br>";
print norm(3,2);
print square(5); // OK
?>
If you don't include the if ($first_time) you get an error saying you can't define
square() twice. Note that square is not local to the function it just appears there. The last line
successfully accesses square in the page scope. This is not terribly useful, but interesting.
--was--
Not sure of the implications of this but...
You can create nested functions within functions but you must make sure they aren't defined
twice, e.g.:
function norm($a, $b) {
static $first_time = true;
if ($first_time) {
function square($x) {
return $x * $x;
}
$first_time = false;
}
return sqrt(square($a) + square($b));
}
print square(5); // error, not defined yet
print norm(5,4);
print "<br>";
print norm(3,2);
print square(5); // OK
If you don't include the if ($first_time) you get an error saying you can't define
square() twice. Note that square is not local to the function it just appears there. The last line
successfully accesses square in the page scope. This is not terribly useful, but interesting.
http://php.net/manual/en/language.variables.scope.php