简体   繁体   中英

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 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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM