Reputation: 8433
Say I've got the following:
<?php
abstract class MyParent
{
public static $table_name;
public static get_all(){
return query("SELECT * FROM {$this->table_name}");
}
public static get_all2(){
return query("SELECT * FROM ".self::table_name);
}
}
class Child extends MyParent
{ public static $table_name = 'child'; }
?>
Assuming that query
is correctly defined, neither of these methods does what I want: get_all() throws Fatal error: Using $this when not in object context in /path/to/foo.php on line xx
because $this
is an instance variable.
and get_all2() throws Fatal error: Undefined class constant 'table_name' in /path/to/foo.php on line xx
because self
is statically determined.
It seems like this kind of thing is the whole point of inheritance, so it should be possible at least easily, if not elegantly. (This is PHP after all.)
What should I be doing?
Upvotes: 3
Views: 1007
Reputation: 10467
You need to change self::table_name
to self::$table_name
- note the dollar sign. But the best way is to use PHP 5.3's static keyword:
http://php.net/manual/en/language.oop5.late-static-bindings.php
The self
keyword references only the class that static proparty was defined, so it is wrong in this case, as you need to get static property 'inherited' from parent class. The keyword 'static' in this case will resolve correct caller class and work correctly.
Upvotes: 5
Reputation: 48314
self::$table_name
, although you probably want static::$table_name
.
Upvotes: 4