Hi,
I dont know what title that is more suitable for this topic but I will try to explain it as well as I can
I have a class that I will use it for interacting with database
I facing a problem when calling the method with "::" assign
here is the code
<?php
class Crud
{
protected $data;
protected $db;
protected $query;
protected static $action;
protected static $instance = null;
protected static $columns = [];
protected $table;
public function __construct()
{
$this->db = new mysqli('localhost', 'root', '', 'bahan_belajar');
if (!$this->db) {
// throw new Exception("Koneksi error", $this->db->errno);
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>';
actually this code was work fine when I put getInstance() method in the first method but how to make it work without putting that method?
example :
$chat = Crud::select('nama', 'teks')->from('chat')->get();
this will produce Fatal error like :
Fatal error: Uncaught Error: Using $this when not in object context in C:\xampp\htdocs\bahan_belajar\chat\classes.php:47 Stack trace: #0 C:\xampp\htdocs\bahan_belajar\chat\classes.php(74): Crud::select('nama', 'teks') #1 {main} thrown in C:\xampp\htdocs\bahan_belajar\chat\classes.php on line 47
I just want to call it with "::" assign and not with "->" assign in first the method
please help me how to solve this
also I am sorry for my bad code structures
thanks in advance