Abstract Static Function in PHP 5.3

后端 未结 2 362
青春惊慌失措
青春惊慌失措 2021-02-04 11:02

I\'m a relative newcomer to PHP, and I\'m figuring out the best way to implement some database access code. I\'m trying to create some simple database access objects -- each ta

2条回答
  •  执念已碎
    2021-02-04 11:41

    Here's your example

    abstract class Table implements iTable {
    
        public static function insert() {
            $class = get_called_class();
            $sql = 'INSERT INTO '.$class::get_class_name();
            echo $sql;
        }    
    
    }
    
    interface iTable {
        static function get_class_name();
    }    
    
    
    class ConcreteTable extends Table
    {
        public function ConcreteTable() {}
    
        static function get_class_name() {
            return 'ConcreteTable';
        }
    
    }
    
    $t = new ConcreteTable();
    $t::insert();
    

    This example respects object paradigm, and you're sure it'll work even if PHP stop support late static bindings (which is a PHP specificity, I think)

    Edit: What both answers show is that it's unknown that an abstract class introduces an interface as well for classes extending from it. Following the template pattern, this is possible in PHP even with static functions (albeit for a good reason that gives you strict standard warnings). The proof of concept:

    abstract class Table
    {
        abstract static function get_class_name();
        public static function insert() {
            printf('INSERT INTO %s', static::get_class_name());
        }    
    
    }
    
    class ConcreteTable extends Table
    {
        public static function get_class_name() {
            return 'ConcreteTable';
        }
    }
    
    ConcreteTable::insert();
    

    If you remove the static keywords here, you actually will get useful (and a standard way of doing things) code:

    abstract class Table
    {
        protected $table = NULL;
        public function insert() {
            printf('INSERT INTO %s', $this->table);
        }    
    
    }
    
    class ConcreteTable extends Table
    {
        protected $table = 'ConcreteTable';
    }
    
    $table = new ConcreteTable();
    ...
    $table->insert();
    

提交回复
热议问题