Класс PHP создан дважды, даже с шаблоном проектирования Singleton - PullRequest
0 голосов
/ 07 февраля 2019

Класс:

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

Счетчик $ всегда равен 2. Я проверил, и функция instance() дважды вводит условие if is_null( self::$_instance ).

Действительно не в состояниисделать этот класс экземпляром только один раз.Пожалуйста, помогите.

1 Ответ

0 голосов
/ 08 февраля 2019

Извините, нашел причину проблемы.

Итак, в 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
}  

И во втором 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

        }
    }
}
...