开发者

Syntax - accessing a class's property's method

开发者 https://www.devze.com 2023-04-02 08:05 出处:网络
I just upgraded my php form mysql to u开发者_JS百科se mysqli in an object oriented approach.I have reason to believe that this code has bug in it.My goal is to use a singlton pattern to guarantee only

I just upgraded my php form mysql to u开发者_JS百科se mysqli in an object oriented approach. I have reason to believe that this code has bug in it. My goal is to use a singlton pattern to guarantee only one database connection per script execution. $db holds the database link.

Can someone verify the line

return $one->$db->query($query);

the syntax looks off.

class one
{
    private static $single = NULL;
    public $db = NULL;
    public function __construct()
    {
        $this->db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
        self::$single=1;
    }
    public static function make_one()
    {
        if(self::$single==NULL)
        {
            return new self();
        }
    }
}


/*database*/

class database
{
    public function __construct()
    {
        one::make_one();
    }
    public static function arche_query($query)
    {
        return $one->$db->query($query);
    }
}


Change it to

return one::make_one->db->query($query);

how ever your singleton pattern is not correct A singleton pattern should create only one instance , in your case its not that case

class one
  {
  private static $_selfInstace;
  public $db;// default is null so no need to assign
  public function __construct()
    {
    $this->db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
    }
    public static function getInstance() 
    {
        if( !(self::$_selfInstace instanceof self) ) {
            self::$_selfInstace= new self();
        }
        return self::$_selfInstace;
    } 
  }

class database
  {
  public function __construct()
    {
    }
  public static function arche_query($query)
    {
    return one::getInstance()->db->query($query);
    }
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号