【问题标题】:PHP Class instanced twice even with Singleton design pattern即使使用单例设计模式,PHP 类也会实例化两次
【发布时间】:2019-02-07 19:20:18
【问题描述】:

类:

if( ! class_exists('MY_CLASS') ) :

class MY_CLASS {

    private static $_instance = null;


    private static $counter = 0;


    private function __construct() {

        self::$counter++;

        // Do stuff here.

        echo "instances: " . self::$counter . "<br>";
    }

    // Other functions here

    public static function instance() {

        if ( is_null( self::$_instance ) ) {

            self::$_instance = new MY_CLASS();
        }
        return self::$_instance;
    }
}


function ctp() {
    return MY_CLASS::instance();
}

// initialize
ctp();

endif; // class_exists check

$counter 始终为 2。我检查过,函数 instance() 两次进入 if 条件 is_null( self::$_instance )

真的不能让这个类只被实例化一次。请帮忙。

【问题讨论】:

  • class 是保留字;你不能为你的班级命名...没有来自你的编辑的抱怨?更一般地说,您应该尝试在命名变量/对象时保持一致,例如我看到你有两个静态变量,一个带下划线,一个没有。看看PSR 以获得一些灵感。
  • 抱歉,为了更清楚,我改了类名。我没有把它当作 CLASS。很抱歉造成混乱......

标签: php singleton instance


【解决方案1】:

抱歉,找到导致问题的原因。

所以在My_Class 我有:

function includes() {

    require_once( 'path-to-second-class.php' );

    // several other requires
}

private function init() {

    // various class instantiations « new Class_Name() », but not for Second_Class
}  

在 second-class.php 我有

class Second_Class {

    $taxs = array();

    function __construct() {

        $this->taxs = ctp()->get_ctp_taxs();        // which returns Main_Class->$taxs

        // do other stuff
    }

    function do_stuff() {

        foreach( $this->taxs as $tax_name => $tax_object ) {

            // do stuff

        }
    }
}

new Second_Class();

由于某种我不知道的原因,这不起作用,所以我将其更改为:

My_Class:

function includes() {

    require_once( 'path-to-second-class.php' );

    // several other requires
}

private function init() {

    // same other instantiations

    new Second_Class();
}  

在 second-class.php 中我现在有了:

class Second_Class {

    function __construct() {

        // do same other stuff
    }

    function do_stuff() {

        foreach( ctp()->get_ctp_taxs() as $tax_name => $tax_object ) {

            // do stuff

        }
    }
}

【讨论】:

    猜你喜欢
    • 2013-06-23
    • 2017-07-29
    • 2014-06-30
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多