Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 835
quodlibetor Avatar asked Jan 31 '26 12:01

quodlibetor


1 Answers

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.

like image 178
Tomasz Kowalczyk Avatar answered Feb 03 '26 03:02

Tomasz Kowalczyk