是否可以在 PHP 中创建静态类(如在 C# 中创建)?

2022-08-30 06:48:55

我想在PHP中创建一个静态类,并让它像在C#中一样运行,所以

  1. 构造函数在首次调用类时自动调用
  2. 无需实例化

这种事情...

static class Hello {
    private static $greeting = 'Hello';

    private __construct() {
        $greeting .= ' There!';
    }

    public static greet(){
        echo $greeting;
    }
}

Hello::greet(); // Hello There!

答案 1

你可以在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!


?>

答案 2

除了 Greg 的答案之外,我还建议将构造函数设置为私有,以便无法实例化该类。

因此,在我看来,这是一个更完整的基于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!


?>

推荐