即使使用Singleton设计模式,PHP类也被实例化两次

时间:2019-02-07 19:20:19

标签: php singleton instance

班级:

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 )

真的不能使此类仅被实例一次。请帮忙。

1 个答案:

答案 0 :(得分:0)

对不起,找到导致问题的原因。

所以在6.0中,我有:

My_Class

在second-class.php中,我有

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
}  

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

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

然后在second-class.php中,我有了:

function includes() {

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

    // several other requires
}

private function init() {

    // same other instantiations

    new Second_Class();
}