是否可以在 PHP 中创建静态类(如在 C# 中)? [英] Is it possible to create static classes in PHP (like in C#)?

查看:20
本文介绍了是否可以在 PHP 中创建静态类(如在 C# 中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a static class in PHP and have it behave like it does in C#, so

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

这种东西...

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

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

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

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

推荐答案

您可以在 PHP 中使用静态类,但它们不会自动调用构造函数(如果您尝试调用 self::__construct()你会得到一个错误).

You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct() you'll get an error).

因此,您必须创建一个 initialize() 函数并在每个方法中调用它:

Therefore you'd have to create an initialize() function and call it in each method:

<?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!


?>

这篇关于是否可以在 PHP 中创建静态类(如在 C# 中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆