Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In PHP, a constructor does not return.</p> <p>So your <code>get</code> method returns a <code>one</code> object, the first time it's called, then a <code>mysqli</code> object. Probably not what you want.</p> <pre><code>if( self::$_db == NULL ) { return new self(); // Here you return an object of class one } else { return self::$_db; // Here you return an object of type mysqli } </code></pre> <p>If you want to return the <code>mysqli</code> object, you do not need a singleton, as there is no need to create an instance of an object that's only here to return an instance of another object.</p> <p>The registry pattern would be better in such a case.</p> <p>If you need to provide methods (a wrapper for your DB object), then create a real singleton.</p> <p><strong>EDIT</strong></p> <p>I checked your updated code. Now you return always the <code>mysqli</code> instance. But you do not need to instantiate your own object. That's completely useless...</p> <p>If you really want to go with your kind of pattern, as golden said, in your static instance, checks if <code>self::db</code> is <code>NULL</code>. If yes, creates the <code>mysqli</code> instance, and assign it to <code>self::db</code>. Then returns it.</p> <pre><code>public static getDatabaseInstance() { if( self::$_db == NULL ) { self::$_db = new mysqli( ... ); } return self::$_db; } </code></pre> <p>Also set the constructor private, so users won't be able to create useless instances of your class. Or better make it public and throw an exception:</p> <pre><code>public function __construct() { throw new Exception( 'This class is not supposed to be instantiated' ); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload