PHP awkward function declaration
Possible Duplicate:
What does it mean to start a PHP function with an ampersand?
Recently I stumbled upon this piece of code:
public static function &get_instance()
{
return self::$instance;
}
What does this kind of function declaration &get_instance()
mean? Can the function name be a variable?
It's part of the singleton pattern, in old-style code.
Singleton is a pattern used to make sure that there is only one instance of a class. (Technically it can be used to make sure that there are a certain number of instances of any class, but that number is almost always one.) It's one of the Gang of Four patterns and you can find endless discussion of its use and abuse all over the web.
It means that the result of get_instance()
is being returned by reference. Since objects are always by reference since PHP 5, it doesn't make sense to write code like that anymore. Incidentally, the public
is also particularly curious, since that means this is PHP 5 code.
上一篇: 函数名称前的“&”是什么?
下一篇: PHP尴尬的函数声明