ale*_*emb 135 php oop static design-patterns
我想在PHP中创建一个静态类,并使其行为与在C#中的行为相同,所以
这种东西......
static class Hello {
private static $greeting = 'Hello';
private __construct() {
$greeting .= ' There!';
}
public static greet(){
echo $greeting;
}
}
Hello::greet(); // Hello There!
Run Code Online (Sandbox Code Playgroud)
Gre*_*reg 195
您可以在PHP中使用静态类,但它们不会自动调用构造函数(如果您尝试调用self::__construct(),则会收到错误).
因此,您必须创建一个initialize()函数并在每个方法中调用它:
<?php
class Hello
{
private static $greeting = 'Hello';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' There!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet(); // Hello There!
?>
Run Code Online (Sandbox Code Playgroud)
Phi*_*hil 50
除了Greg的回答之外,我还建议将构造函数设置为private,以便无法实例化该类.
所以在我的拙见中,这是一个基于Greg的更完整的例子:
<?php
class Hello
{
/**
* Construct won't be called inside this class and is uncallable from
* the outside. This prevents instantiating this class.
* This is by purpose, because we want a static class.
*/
private function __construct() {}
private static $greeting = 'Hello';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' There!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet(); // Hello There!
?>
Run Code Online (Sandbox Code Playgroud)
And*_*air 24
你可以拥有那些"静态"类.但我想,缺少一些非常重要的东西:在php中你没有应用程序循环,所以你不会在整个应用程序中获得真正的静态(或单例)...
final Class B{
static $staticVar;
static function getA(){
self::$staticVar = New A;
}
}
Run Code Online (Sandbox Code Playgroud)
b 的结构称为单例处理程序,您也可以在 a 中执行此操作
Class a{
static $instance;
static function getA(...){
if(!isset(self::$staticVar)){
self::$staticVar = New A(...);
}
return self::$staticVar;
}
}
Run Code Online (Sandbox Code Playgroud)
这是单例使用
$a = a::getA(...);