您好,我想问一下如何从其他类附带的函数postData()中获取$ manufacturer和$ id。这样我就可以将其传递给我的模型了。谢谢你。
class postDataManager{
public function postData(){
$manufacturer = $_POST['manufacturer'];
$id = $_POST['id'];
}
}
class manufactureController extends postDataManager{
private $model;
public function __construct(){
$this->model = new manufacturerModel();
$postDataManager= new postDataManager();
}
public function addManufacturer(){ //get the add function
//here i need access for the variable $manufaturer from class postData function
$this->model->addProcess($manufacturer);
}
public function updateManufacturer(){ //get the update function
//here i need access for the variable $manufaturer and $id from class postData function
$this->model->updateProcess($id, $manufacturer);
}
}
当前,这两个变量一旦postData()
离开方法便会丢失,因为它们属于方法的本地范围。您需要为其定义属性。
看一下这个修改后的示例:
<?php
class manufacturerModel {
}
class postDataManager {
protected $id;
protected $manufacturer;
public function __construct($manufacturer, $id) {
$this->manufacturer = $manufacturer;
$this->id = $id;
}
}
class manufactureController extends postDataManager {
private $model;
public function __construct($manufacturer, $id) {
parent::__construct($manufacturer, $id);
$this->model = new manufacturerModel();
}
public function addManufacturer() { //get the add function
$this->model->addProcess($this->manufacturer);
}
public function updateManufacturer() { //get the update function
$this->model->updateProcess($this->id, $this->manufacturer);
}
public function echoContent() {
echo sprintf("manufacturer: %s\nid: %s\n", $this->manufacturer, $this->id);
}
}
// some example values
$_POST['manufacturer'] = "Manufactum Ltd.";
$_POST['id'] = 17397394;
$controller = new manufactureController($_POST['manufacturer'], $_POST['id']);
$controller->echoContent();
现在,这些值以持久方式存储在对象中。由于第二个类扩展了第一个类,因此这些属性也是从该派生类实例化的对象的一部分,因此您可以使用$this
引用同样地访问它们,除非已private
在该类中声明了它们。
上面的演示代码的输出是:
manufacturer: Manufactum Ltd.
id: 17397394
这些是OOP(面向对象编程)的基础,每个教程都对此进行了说明。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句