Home >php教程 >PHP源码 >php5.3匿名函数实现单例模式

php5.3匿名函数实现单例模式

PHP中文网
PHP中文网Original
2016-05-25 16:59:161259browse

从laravel源码中看到的,学习下。
执行代码返回如下信息:
init
string 'msg' (length=3)
string 'msg' (length=3)
init
string 'msg2' (length=4)
init
string 'msg3' (length=4)
string 'msg3' (length=4)
string 'msg3' (length=4)

php代码

class cc {
 
    function normal($a)
    {
        static $object;
 
        if (is_null($object))
        {
            echo 'init';
            $object = $a;
        }
 
        return $object;
    }
 
    public function share($p)
    {
        return function() use ($p)
        {
            static $object;
 
            if (is_null($object))
            {
                echo 'init';
                $object = $p;
            }
 
            return $object;
        };
    }
 
}
 
$c = new cc();
 
$msg = $c->share('msg');
var_dump($msg());
var_dump($msg());
$msg2 = $c->share('msg2');
var_dump($msg2());
 
$msg3 = $c->normal('msg3');
var_dump($msg3);
var_dump($msg3);
$msg4 = $c->normal('msg4');
var_dump($msg4);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn