开发者

What's the Right Way to access static properties of subclasses in static methods of superclasses in PHP?

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 i开发者_如何学JAVAs 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?


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.


self::$table_name, although you probably want static::$table_name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜