您好,我想在 php 中学习单例模式,我有一门课:
class Database
{
private static $instance;
private function __construct()
{
}
public static function getInstance()
{
if (!self::$instance)
{
self::$instance= new Database();
}
return self::$instance;
}
public function query($table)
{
$this->query = 'select * from $table';
}
public function result()
{
echo $this->query;
}
}
$db = Database::getInstance();
现在,是否可以调用 result() 方法并使用单例打印由 query() 设置的值,即“select * from $table”?
我希望我的代码类似于:
$db->query('user_tb')->result();
//output
select * from user_tb;