PHP - Extending Class

后端 未结 2 1643
清酒与你
清酒与你 2020-12-14 12:02

I\'ve done lots and lots of code in PHP that is object-oriented, but up until now, all of my classes have been, \"singular\", I suppose you can call it. I am in the process

相关标签:
2条回答
  • 2020-12-14 12:15

    You could try late static binding as mentioned below, or a singleton solution should work as well:

    <?php
    abstract class DatabaseObject {
      private $table;
      private $fields;
    
      protected function __construct($table, $fields) {
        $this->table = $table;
        $this->fields = $fields;
      }
    
      public function find_all() {
        return $this->find_by_sql('SELECT * FROM ' . $this->table);
      }
    }
    
    class Topics extends DatabaseObject {
      private static $instance;
    
      public static function get_instance() {
        if (!isset(self::$instance)) {
          self::$instance = new Topics('master_cat', array('cat_id', 'category'));
        }
    
        return self::$instance;
      }
    }
    
    Topics::get_instance()->find_all();
    
    0 讨论(0)
  • 2020-12-14 12:27

    You should look into the concept of Late Static Binding in PHP. This allows you to access a static constant or function from the class that was called.

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