Search code examples
phplate-static-binding

Assigning a class variable from subclass without constructor


lI am building a light-weight Model layer for my project's database access. I would like it to be in the spirit of Ruby on Rails. Instead of instantiating a new Model object, I want to use a singleton approach. Here is the current issue I am facing:

class BaseModel {
    public static $name;
    public static function get($id) {
        echo "SELECT * FROM ". self::$name ."s WHERE ". self::$name .' = '.$id;
    }
}

class Customer extends BaseModel {
    //parent::$name = 'customer'; => ERROR
}

$c = Customer::get(4);

Is there some way to assign the parent's static members in the class body? I would like to avoid creating an actual singleton class if possible. Thanks.


Solution

  • The feature you are looking for is called Late Static Binding (LSB) and thankfully has been introduced to PHP in 5.3. You may read about it here: http://php.net/manual/en/language.oop5.late-static-bindings.php

    This is your code rewritten using LSB.

    <?php
    
    class BaseModel {
        public static $name;
        public static function get($id) {
            echo "SELECT * FROM ". static::$name ."s WHERE ". static::$name .' = '.$id;
        }
    }
    
    class Customer extends BaseModel {
        public static $name = 'customer';
    }
    
    $c = Customer::get(4);
    ?>