我想在PHP中创建一个静态类,并使其行为像在C#中一样,所以
这种东西…
static class Hello { private static $greeting = 'Hello'; private __construct() { $greeting .= ' There!'; } public static greet(){ echo $greeting; } } Hello::greet(); // Hello There!
您可以在PHP中拥有静态类,但它们不会自动调用构造函数(如果尝试调用self::__construct(),则会收到错误)。
self::__construct()
因此,您必须创建一个initialize()函数并在每个方法中调用它:
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! ?>