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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/468642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:51:18  来源:igfitidea点击:

Is it possible to create static classes in PHP (like in C#)?

phpdesign-patternsoopstatic

提问by aleemb

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

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

  1. Constructor is automatically called on the first call to the class
  2. No instantiation required
  1. 构造函数在第一次调用类时自动调用
  2. 无需实例化

Something of this sort...

这种东西...

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

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

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

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

回答by Greg

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).

您可以在 PHP 中使用静态类,但它们不会自动调用构造函数(如果您尝试调用self::__construct(),则会出现错误)。

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

因此,您必须创建一个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!


?>

回答by Phil

In addition to Greg's answer, I would recommend to set the constructor private so that it is impossible to instantiate the class.

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

So in my humble opinion this is a more complete example based on Greg's one:

所以在我看来,这是一个基于 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!


?>

回答by Andreas Niedermair

you can have those "static"-like classes. but i suppose, that something really important is missing: in php you don't have an app-cycle, so you won't get a real static (or singleton) in your whole application...

你可以拥有那些“静态”类的类。但我想,缺少一些真正重要的东西:在 php 中你没有应用程序周期,所以你不会在整个应用程序中获得真正的静态(或单例)......

see Singleton in PHP

参见PHP 中的单例

回答by borrel

final Class B{

    static $staticVar;
    static function getA(){
        self::$staticVar = New A;
    }
}

the stucture of b is calld a singeton handler you can also do it in a

b 的结构称为单例处理程序,您也可以在 a 中执行

Class a{
    static $instance;
    static function getA(...){
        if(!isset(self::$staticVar)){
            self::$staticVar = New A(...);
        }
        return self::$staticVar;
    }
}

this is the singleton use $a = a::getA(...);

这是单例使用 $a = a::getA(...);

回答by dave.zap

I generally prefer to write regular non static classes and use a factory class to instantiate single ( sudo static ) instances of the object.

我通常更喜欢编写常规的非静态类并使用工厂类来实例化对象的单个( sudo static )实例。

This way constructor and destructor work as per normal, and I can create additional non static instances if I wish ( for example a second DB connection )

这样构造函数和析构函数正常工作,如果我愿意,我可以创建额外的非静态实例(例如第二个数据库连接)

I use this all the time and is especially useful for creating custom DB store session handlers, as when the page terminates the destructor will push the session to the database.

我一直在使用它,对于创建自定义数据库存储会话处理程序特别有用,因为当页面终止时,析构函数会将会话推送到数据库。

Another advantage is you can ignore the order you call things as everything will be setup on demand.

另一个优点是您可以忽略调用事物的顺序,因为一切都将按需设置。

class Factory {
    static function &getDB ($construct_params = null)
    {
        static $instance;
        if( ! is_object($instance) )
        {
            include_once("clsDB.php");
            $instance = new clsDB($construct_params);   // constructor will be called
        }
        return $instance;
    }
}

The DB class...

数据库类...

class clsDB {

    $regular_public_variables = "whatever";

    function __construct($construct_params) {...}
    function __destruct() {...}

    function getvar() { return $this->regular_public_variables; }
}

Anywhere you want to use it just call...

任何你想使用它的地方只需调用...

$static_instance = &Factory::getDB($somekickoff);

Then just treat all methods as non static ( because they are )

然后将所有方法视为非静态方法(因为它们是)

echo $static_instance->getvar();

回答by borrel

object cannot be defined staticly but this works

对象不能静态定义,但这有效

final Class B{
  static $var;
  static function init(){
    self::$var = new A();
}
B::init();