note 119475 deleted from language.oop5.anonymous by cmb
| From: | cmb@php.net | Date: | Wed, 22 Jun 2016 17:11:13 +0000 |
| Subject: | note 119475 deleted from language.oop5.anonymous by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-205780@lists.php.net to get a copy of this message | ||
Note Submitter: web_steel
----
>>
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
?>