2

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 
Eva Dias
  • 1,709
  • 9
  • 36
  • 67
Basha Man
  • 27
  • 5
  • 1
    [Use global variables in a class](http://stackoverflow.com/questions/11923272/use-global-variables-in-a-class/11923384#11923384) – PeeHaa Sep 03 '12 at 20:44
  • 2
    No! Please don't user global variables ever! Except in VERY seldom cases. – SteAp Sep 03 '12 at 20:54

1 Answers1

0

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

msEmmaMays
  • 1,073
  • 7
  • 7
  • That is the problem i am not having 5.3 in the server, i do understand that will solve the problem be the main issue is that the function does not realy have a problem the only problem how can i initialize the table name according to the child class requirement or to be more specific child table. – Basha Man Sep 03 '12 at 20:57
  • You can't do it with static functions before v5.3... I had this same exact problem and ended up just upgrading to php 5.3.... Sure you can rewrite your code to get around it by adding a bunch of extra functions, but that kind of defeats the point of extending the class in the first place - Bottom line - You have to upgrade to 5.3 eventually, why not just save time and do it now? (spend time re-coding or spend time upgrading?) – msEmmaMays Sep 03 '12 at 21:04