note 119475 added to language.oop5.anonymous
| From: | web_steel | Date: | Wed, 15 Jun 2016 22:30:47 +0000 |
| Subject: | note 119475 added to language.oop5.anonymous | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-205731@lists.php.net to get a copy of this message | ||
>>
Unlike anonymous functions, returning an anonymous class from a function will be a new instance of
the SAME anonymous class each time.
<?php
function anonymous_function () {
return function () {
static $shared = 0;
echo ++$shared;
};
};
function anonymous_class() {
return new class {
static $shared = 0;
public function __construct() {
echo ++self::$shared;
}
};
}
anonymous_function(); // outputs 1
anonymous_function(); // outputs 1
anonymous_class(); // outputs 1
anonymous_class(); // outputs 2
get_class(anonymous_class()) === get_class(anonymous_class()); // TRUE
?>
When you call the anonymous_function(); There will be no echo, and just create an anonymous
function. It will be correct as follows:
<?php
$fitst_function = anonymous_function(); //create fist anonymous function
$second_function = anonymous_function(); //create second anonymous function
$first_function(); // outputs 1
$first_function(); // outputs 2
$first_function(); // outputs 3
$second_function(); // outputs 1
$second_function(); // outputs 2
?>
----
Server IP: 72.52.91.14
Probable Submitter: 46.53.177.14
----
Manual Page -- http://php.net/manual/en/language.oop5.anonymous.php
Edit -- https://master.php.net/note/edit/119475
Del: integrated -- https://master.php.net/note/delete/119475/integrated
Del: useless -- https://master.php.net/note/delete/119475/useless
Del: bad code -- https://master.php.net/note/delete/119475/bad+code
Del: spam -- https://master.php.net/note/delete/119475/spam
Del: non-english -- https://master.php.net/note/delete/119475/non-english
Del: in docs -- https://master.php.net/note/delete/119475/in+docs
Del: other reasons-- https://master.php.net/note/delete/119475
Reject -- https://master.php.net/note/reject/119475
Search -- https://master.php.net/manage/user-notes.php