从子类初始化父类变量

时间:2012-09-03 20:41:56

标签: php

我有两个类:一个是包含常规数据库查询的DBobject,另一个是具有特定数据库查询的其他子类。现在问题是当我尝试初始化父类table_name变量时,它没有被初始化。我尝试了很多方法,但它表明在执行查询时表是空的。这是代码:

<?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";
}
?>


?>

主要应用:

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


 ?>

我希望能够初始化DBobject函数find_all()将使用的表的类型。 请帮我解决一下这个。这是我得到的错误。请注意,查询不包含表的名称。

 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 

1 个答案:

答案 0 :(得分:0)

如果您使用的是php 5.3或更高版本,则可以执行此操作,因为他们添加了“后期静态绑定”

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

你可以使用get_called_class()或static ::(而不是self::)来引用CALLED的类而不是代码所在的类