1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Naveen Margan
  • 58
  • 1
  • 9
  • Did you try the late static binding ? static::sql_finder() instead of self::sql_finder() ? – Oussama Jilal Aug 02 '12 at 14:07
  • Hi Naveen. Could I ask you to try to capitalise 'I' and format code blocks/inline where possible? Making it as readable as possible helps everyone, including those whose first language isn't English. Thanks! – halfer Aug 02 '12 at 14:13
  • Hi halfer , i am new and infact this is my first question , ill consider your words hereafter , thankyou – Naveen Margan Aug 03 '12 at 05:26
  • Yazmat , i tried still no use , anyway looks like get_called_class() was missing in my code , made clear below by great people – Naveen Margan Aug 03 '12 at 05:28

2 Answers2

3

Two things you will find helpful related to this:

  • get_called_class() instead of get_class()
  • static::foo() instead of self::foo()
Matthew
  • 47,584
  • 11
  • 86
  • 98
0

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'
    }
}
Constantine
  • 119
  • 8
  • Doesn't really answer the question, although I do think that a non-static solution is generally preferable. – Matthew Aug 02 '12 at 14:10