Programing

PHP에서 정적 클래스를 만들 수 있습니까 (C # 에서처럼)?

crosscheck 2020. 6. 26. 08:16
반응형

PHP에서 정적 클래스를 만들 수 있습니까 (C # 에서처럼)?


PHP에서 정적 클래스를 만들고 C #에서와 같이 동작하도록하고 싶습니다.

  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()하면 오류가 발생합니다).

따라서 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!


?>

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!


?>

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

see Singleton in PHP


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

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


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

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();

object cannot be defined staticly but this works

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

참고URL : https://stackoverflow.com/questions/468642/is-it-possible-to-create-static-classes-in-php-like-in-c

반응형