1

I have class DbTable, which implements all db queries to database such as insertRecord, updateRecord, ... But variable is not rewriting.

abstract class DbTable {
    public static $table;

    public static function insertRecord($data) {
       // here I add some values to data, but that's not important
       my_db::insert(self::$table, $data);
    }
}

class User extends DbTable {
    public static $table = 'table_users';
}

// everywhere I can call
User::insertRecord($data);

I know I can call

$c = get_called_class();
my_db::insert($c::$table, $data);

but I think that's not best solution at all.

Method and variables can be non static, I just use them because it is comfortable to write User::insertRecord instead of $user = new User(); $user->insertRecord($data);

Jens
  • 67,715
  • 15
  • 98
  • 113
Manic Depression
  • 1,000
  • 2
  • 16
  • 34

2 Answers2

0

When you're working with static classes you need to specify your variable source, in this case you're scoping to both classes and not on single class, this makes a difference, because self is scoping to concurrent class and when you want to scope for both classes you have to use static.

/**
* For testing
*/
class my_db {
    public static function insert($table, $data){
        echo $table;
    }
}
abstract class DbTable {
    public static $table = null;

    public static function insertRecord($data) {

        //self::$table is empty
        //static::$table has 'table_users'

        // here I add some values to data, but that's not important
        my_db::insert(static::$table, $data);
    }
}

class User extends DbTable {
    public static $table = 'table_users';
}

// everywhere I can call
User::insertRecord(['Hi']);

self::$table is empty

static::$table has 'table_users'

You can read more about this here: SO Answer and PHP Documentation

Community
  • 1
  • 1
VeeeneX
  • 1,556
  • 18
  • 26
0

Use static variables are unnecessary in this case. You just need dynamically create User object and them call method.

abstract class DbTable
{
    protected $tableName;

    public static function insertRecord($data) 
    {
        $object = static::newInstance();
        $object->insert($data);
    }

    public static function newInstance()
    {
        $className = get_called_class();
        return new $className();
    }

    public function insert($data)
    {
        my_db::insert($this->tableName, $data);
    }
}

class User extends DbTable 
{
    public function __construct()
    {
        $this->tableName = 'table_users';
    }
}

You can now call:

User::insertRecord(['col1' => 'val1']);

But also you can insert rows from instated object:

$user = new User();
$user->insert(['col1' => 'val1']);
Piotr Olaszewski
  • 6,017
  • 5
  • 38
  • 65