因为当我声明一个单例来处理单个实例时,在最后使用相同实例执行操作时它不起作用,因为select和from不会连接变量以便能够在同一个实例中显示它?
<?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 );
结果是:
Null
但我希望结果:SELECT * <br /> FROM TABLE1 <br />
如何将值保存在同一个实例中?
答案 0 :(得分:0)
你最好将$ sql变量设为private:
private static $sql = null;
并添加新方法getSQL():
public function getSQL() {
return self::$sql;
}
如果要读取SQL查询,最后调用此方法:
var_dump( singleton::instance()->getSQL() );