Bonjour, j'ai un problème d'initialisation avec mon singleton :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| <?php
if( ! class_exists( 'Lib_Session' ) )
{
class Lib_Session
{
protected static $o_Instance;
protected function __construct()
{
$handle = fopen( "C:\\Log.txt", 'a+' );
$string = "In __construct() \n";
fwrite( $handle, $string );
fclose( $handle );
}
public static function GetInstance()
{
$handle = fopen( "C:\\Log.txt", 'a+' );
$string = "In GetInstance() \n";
fwrite( $handle, $string );
fclose( $handle );
if( ! self::$o_Instance instanceof self )
self::$o_Instance = new self;
return self::$o_Instance;
}
}
} |
En effet si vous regardes le fichier de logs situé à la racine du disque dur et généré par ces lignes :
1 2 3 4
| $handle = fopen( "C:\\Log.txt", 'a+' );
$string = "In ... \n";
fwrite( $handle, $string );
fclose( $handle ); |
vous obtenez les logs suivants :
In GetInstance()
In __construct()
In GetInstance()
In __construct()
Dans un autre fichier j'initialise mon singleton comme ça :
$this->o_Session = Lib_Session::GetInstance();
Si je commente cette ligne, mon fichier de logs reste vierge, prouvant qu'aucun autre appel à GetInstance() n'est effectué ailleurs dans le programme.
Alors pourquoi ma fonction GetInstance() est-elle appelée deux fois ?
Et surtout pourquoi mon constructeur __construct() également ?
Merci pour votre aide.
Partager