0

because when I declare a singleton to handle a single instance, when performing the operation with the same instance at the end it does not work, because select and from does not concatenate the variable to be able to show it in the same instance?

<?php
class singleton{
    protected static $instance = null;
    public static $sql = null;

    public function __construct(){}
    private final function __clone() { }

    public static function instance() {
        if ( self::$instance  == NULL ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function select(){
        self::$sql = "SELECT *  <br />";
        return new static;
    }

    public function from(){
        self::$sql .= "FROM TABLE1 <br />";
        return new static;
    }

}
singleton::instance()->select();

singleton::instance()->from();

var_dump( singleton::instance()->sql );

The result is:

Null

But I expect result: SELECT * <br /> FROM TABLE1 <br />

How can I keep the values ​​within the same instance?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Lenin Zapata
  • 1,417
  • 1
  • 11
  • 14
  • You are solving the wrong problem. You do not need the Singleton in the first place. Create one instance and then use Dependency Injection to make the instance available to code that needs it. See https://stackoverflow.com/a/4596323/208809 – Gordon Jun 18 '18 at 06:54

1 Answers1

0

You better should make $sql variable as private:

    private static $sql = null;

and add new method getSQL():

public function getSQL() {
    return self::$sql;
}

and finally call this method if you want to read a SQL query:

var_dump( singleton::instance()->getSQL() );
MrSmile
  • 1,217
  • 2
  • 12
  • 20