PHP - class extension

I have done a lot and a lot of code in PHP, object oriented, but so far all my classes have been โ€œsingleโ€, I suppose you can call it that. I am in the process of changing several classes (which have approximately 5 of the same methods) to extend one class (to get rid of code duplication). I am facing a few issues.

I am trying to access the method in the parent class, but you can see the problem.

Parent class:

class DatabaseObject { public static function find_all() { return self::find_by_sql("SELECT * FROM " . self::$table_name); } } 

Child class:

 class Topics extends DatabaseObject { protected static $table_name = "master_cat"; protected static $db_fields = array('cat_id', 'category'); public $cat_id; public $category; } 

The code tries to access all the information from this table from the php / html file:

 $topics=Topics::find_all(); foreach($topics as $topic): echo $topic->category; endforeach; 

As you can see, most of the code has not been combined with a new way of doing things. I need to change self :: $ table_name, which no longer works in a new way, I am doing something. I will have about 5 classes extending this object, so the best way to encode this so that I can access different tables using one method (instead of including this exact find_all () method in 5 different classes.

+8
php class extends object-oriented-database
source share
2 answers

You can try using the last 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(); 
+18
source share

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

+2
source share

All Articles