In a table class I want to use simple functions but also static functions, how can I do? Here is my current code (which does not work)
In my controller, I just want to do: Table::get('posts')
which directly invokes the function check_table($table)
.
<?php
namespace Fwk\ORM;
use Fwk\Application;
use Fwk\Database\Database;
class Table extends Application {
public function __construct()
{
$this->db = new Database();
}
public static function get($table) {
if($this->check_table($table)) {
return "ok";
}
}
public function check_table($table) {
$r = $this->$db->query("SELECT 1 FROM $table");
return $r;
}
}
?>
You have to understand exactly what static
means. When you declare a method as static, you're essentially saying "This method can be called directly without actually instantiating it's class". So while you're in a static method, you won't have access to $this
since you're not in object context.
You could make check_table()
static also and use it as a sort of factory:
public static function get($table) {
if(self::check_table($table)) {
return "ok";
}
}
public static function check_table($table) {
$r = (new Database())->query("SELECT 1 FROM $table");
return $r;
}