【发布时间】:2017-12-10 06:02:04
【问题描述】:
我想创建自己的类,用于与数据库交互, 如果我使用方法链接,我认为它会很容易和可读。 但是我在静态调用第一个方法时遇到了问题。
代码如下:
<?php
class Crud
{
protected static $action;
protected static $instance = null;
protected static $columns = [];
protected $data;
protected $db;
protected $query;
protected $table;
public function __construct()
{
$this->db = new mysqli('localhost', 'root', '', 'bahan_belajar');
if (!$this->db) {
echo "error";
}
return $this;
}
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self;
}
return self::$instance;
}
public function select()
{
if (empty(func_get_args())) {
// $this->columns = "*";
self::$columns = "*";
} else {
if (is_array(func_get_args())) {
// self::columns = join(', ', func_get_args());
self::$columns = join(', ', func_get_args());
} else {
// self::columns = func_get_args();
self::$columns = func_get_args();
}
}
self::$action = "SELECT";
return $this;
}
public function from($tableName)
{
$this->table = ' FROM ' . $tableName;
return $this;
}
public function get($getName = 'object')
{
$this->query = self::$action . ' ' . self::$columns . ' ' . $this->table;
switch ($getName) {
case 'object':
$this->data = $this->db->query($this->query)->fetch_object();
break;
case 'array':
$this->data = $this->db->query($this->query)->fetch_array();
break;
case 'count':
$this->data = $this->db->query($this->query)->num_rows;
break;
}
return $this->data;
}
}
$chat = Crud::getInstance()->select('nama', 'teks')->from('chat')->get();
echo '<pre>';
print_r($chat);
echo '</pre>';
实际上,如果我首先使用getInstance() 方法,如上所示,此代码可以正常工作。但是,当我直接调用 select() 方法作为静态方法时,如何使它工作,例如:
$chat = Crud::select('nama', 'teks')->from('chat')->get();
如果我运行上面的代码,我会得到一个错误,例如:
致命错误:未捕获的错误:在 C:\xampp\htdocs\bahan_belajar\chat\classes.php:47 的对象上下文中使用 $this 堆栈跟踪:#0 C:\xampp \htdocs\bahan_belajar\chat\classes.php(74): Crud::select('nama', 'teks') #1 {main} 在 C:\xampp\htdocs\bahan_belajar\chat\classes 中抛出。 php上线47
我知道 select() 方法应该是静态方法,然后才能使用 :: 调用(我认为),但我怎样才能使其成为静态方法?
【问题讨论】:
-
您只能将
::与静态方法一起使用,->与实例方法一起使用。您需要使用静态方法获取一个实例,然后使用->进行链接,如下所示:Crud::getInstance()->select('nama', 'teks')->from('chat')->get(); -
是的,感谢您的评论。目前我仍然想知道如何在 select() 方法上应用静态,并且可以跟
->分配其他方法。我仍然不知道如何解决这个问题:( -
查看我更详细的答案。简短的版本是可以使用魔术方法让您在需要时假装实例方法是静态方法,但这并不容易。
标签: php oop static-methods method-chaining