如何使用extend从其他类访问变量?

时间:2017-02-03 17:09:52

标签: php model-view-controller

你好我想问一下如何从包含在其他类中的函数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);
   }
}

3 个答案:

答案 0 :(得分:1)

目前,只有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(面向对象编程)的基础知识,每个教程都会对此进行解释。

答案 1 :(得分:0)

创建名称为$ manufacturer且$ id

的属性
class postDataManager{
   protected $manufacturer;
   protected $id;
   public function postData($manufacturer){
       $this->manufacturer = $_POST['manufacturer'];
       $this->id = $_POST['id'];  
   }
}

现在您可以使用子类

进行访问

答案 2 :(得分:0)

您应该在postDataManager类和postData函数中声明$manufacturer$id变量,然后使用$this->manufacturer=$_POST['manufacturer'];$this->id=$_POST['id'];