简体   繁体   中英

Initializing Parent class variable from the child class

I have 2 classes: one is an DBobject which contains general database query and the other child classes that each has a specific database query. Now the problem is when I try to initialize the parent class table_name variable it is not being initialized. I have tried many ways but it shows that the table is empty when the query is performed. Here's the code:

<?php
class DBobject {

 public static $table_name="";

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

 }
?>


<?php
class Catagory extends DBobject{
 public static $table_name ="catagory";
}
?>


?>

The main application:

<?php
$cata = Catagory::find_all();
     foreach($cata as $catag){
     echo "Catagory Name :" . $catag->name."<br/>";
} 


 ?>

I want to be able to initialize the type of the table that the DBobject function find_all() will work on. Please help me with this. This is the error that I get. Noticet that the query does not contain the name of the table.

 Database query Failed You have an error in your SQL syntax; check the manual that corresponds to  your MySQL server version for the right syntax to use near '' at line 1

last SQL query: SELECT * FROM 

If you are on php 5.3 or above, you can do this because they added 'late static bindings'

http://php.net/manual/en/language.oop5.late-static-bindings.php

you can use get_called_class() or static:: (instead of self::) to reference the class that was CALLED instead of the class the code is in

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM