Domanda

I have a separate classes for each MySQL table I have in my PHP project. The class would be something like this:

class students  {

  public static function find_all() {
        return self::sql_finder("SELECT * FROM ".get_class());
  }

}

I use the same class for almost all the table I have in my project, except I change the class name as table name. Now you can see I used "get_class()" in the function used in the class, so the SQL takes the table name from the class name.

Since I have too many functions in the class which I use in all the classes, I plan to extend the class with the sub class something like this:

class  class_with_all_the_common_functions {
 public static function find_all() {
        return self::sql_finder("SELECT * FROM ".get_class());
  }
}

class student extends class_with_all_the_common_functions {
 // some table specific functions
}

Now when I use student::find_all() it shows an error:

Database query failed: Table 'dr.class_with_all_the_common_functions
doesn't exist

I think it makes the point clear, I want the find_all() to be executed as it is executing in the class student. Is that something which is possible through late static binding?

È stato utile?

Soluzione

Two things you will find helpful related to this:

  • get_called_class() instead of get_class()
  • static::foo() instead of self::foo()

Altri suggerimenti

You may use get_class(parent) or make private field with table name and overload it only when it nessessary:

class A {
    private $table = 'A';
}

class B extends A {
    public function getTable() {
        return $this->table; //will return 'A'
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top