简体   繁体   English

从子类初始化父类变量

[英]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. 我有2个类:一个是包含常规数据库查询的DBobject,另一个是每个都有特定数据库查询的子类。 Now the problem is when I try to initialize the parent class table_name variable it is not being initialized. 现在的问题是,当我尝试初始化父类table_name变量时,它尚未初始化。 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. 我希望能够初始化DBobject函数find_all()可以使用的表的类型。 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' 如果您使用的是php 5.3或更高版本,则可以这样做,因为它们添加了“后期静态绑定”

http://php.net/manual/en/language.oop5.late-static-bindings.php 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 您可以使用get_ Called_class()或static::(而不是self::)来引用已调用的类,而不是代码所在的类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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