Abstract Static Function in PHP 5.3

后端 未结 2 365
青春惊慌失措
青春惊慌失措 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();
    
    0 讨论(0)
  • 2021-02-04 11:46

    An abstract function will never be static, in any kind of language.

    A static function provide a functionality, even if there is no instance.

    An abstract function doesn't provide any functionnality.

    Logically, you can't use an abstract static function, which would --ALWAYS AND NEVER-- provide a functionnality.


    B extends A

    When you call a static function in B context, it'll be runned in A context (cause of static state).

    But, in A context, this same function is abstract, an you're not allowed to call it.

    0 讨论(0)
提交回复
热议问题