2014-10-02 115 views
2

我试图制作一个表,但对于不同的页面,我需要不同类型的变量。我想通过在父类中进行总体布局来完成此操作,然后将所有细节放在扩展类中。但是,我不知道如何从扩展类中获取信息返回到父类。如何从扩展类中获取变量到其父类中

父类:

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

嗯......'$ this-> whatever'? – 2014-10-02 14:03:40

+0

逻辑上,必须在父类中访问的属性应在父类中定义,但是当前的代码将工作得很好 - 请参阅:http://codepad.viper-7.com/UIHgFc – Steve 2014-10-02 14:15:25

回答

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'; 
    } 
} 
+0

您的解决方案解决了我的问题问题!我使用了替代方法,并且唯一改变的是在$ this-> table_part_xyz(0)部分放置了一个0,导致浏览器一直说没有定义变量,无论我放在括号之间。 – 2014-10-02 14:54:30

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'; 
    } 
} 
0

您可以在父类中的抽象功能,RET窃取所需的变量,并在返回适当的子类中覆盖它。

我一直没有使用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, ...); 
    } 
}