我试图制作一个制作类的表,但对于不同的页面,我需要不同类型的变量。我想通过在父类中使用一般布局然后将所有细节放在扩展类中来实现。但是,我不知道如何从扩展类中获取信息回到父类。
家长班:
class table {
protected $tablename;
protected $mysqli;
function set_name($name) {
$this->tablename = $name;
}
function connectdb($mysqli) {
$this->mysqli = $mysqli;
}
function make_table($tablename) {
//all table making stuff
//here I want to access the completed variable
}
扩展课程:
class tasktable extends table {
public $completed;
function set_completed($completed) {
$this->completed = $completed;
echo $completed;
}
function get_completed() {
return $this->completed;
}
}
页面上的代码:
$tasktable1 = new tasktable($tableName);
$tasktable1->connectdb($mysqli);
$tasktable1->set_completed(0);
$tasktable1->make_table($tableName);
答案 0 :(得分:1)
很难从你对基类的定义中看出来,但你可以从两个方面来解决这个问题。
第一个选项是使父类和make_table()
方法抽象,让子类定义整个方法:
abstract class table
{
// ...
abstract function make_table($tablename);
}
然后,在您的专门子类中,您将覆盖make_table()
方法:
class tasktable extends table
{
// ...
function make_table($tablename)
{
// all table making stuff
// you can reference parent::make_table($tablename) if you want
}
}
或者,您将构成表的方法声明为抽象,然后从父类中的make_table()
调用它们。
abstract class table
{
abstract function table_part_xyz($name);
function make_table($tablename)
{
// do stuff and call $this->table_part_xyz($tablename);
}
}
然后,在子类中:
class tasktable extends table
{
function table_part_xyz($name)
{
return 'foobar';
}
}
答案 1 :(得分:1)
这里最好的选择是使用抽象的getter和setter来处理你需要在子类中定义但可以由父类访问的所有内容
例如
abstract class parentClass
{
/**
* @return mixed
*/
abstract protected function getThing1();
/**
* @return mixed
*/
abstract protected function getThing2();
protected function doingThings()
{
$thing1 = $this->getThing1();
$thing2 = $this->getThing2();
}
}
class childClass extends parentClass
{
protected function getThing1()
{
return 'thing1';
}
protected function getThing2()
{
return 'thing2';
}
}
答案 2 :(得分:0)
您可以在父类中使用抽象函数,该函数检索所需的变量,并在子类中覆盖它并返回适当的变量。
我还没有使用PHP一段时间,我会在这里使用一些伪代码,请原谅我的语法问题。
class Parent {
abstract getVariables();
function makeTable()
{
var $fields = $this->getVariables();
// ... do whatever you want
}
}
class Child extends Parent {
override function getVariables() {
return array($this->completed, $this->otherVariable, ...);
}
}