2017-02-03 111 views
0

你好,我想問一下如何從函數postData()中獲得$ manufacturer和$ id,這個函數包含在其他類中。所以我可以將它傳遞給我的模型。謝謝。如何使用extend從其他類訪問變量?

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); 
    } 
} 

回答

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(面向對象編程)的基本知識,這是在每一個教程說明。

+0

對不起,我剛剛開始學習面向對象。我怎麼可以稱他們爲我的模型..就像現在我在模型公共職能addProcess($製造商){} –

+0

我試圖回聲用戶輸入。它不反映用戶輸入@arkascha –

+0

@GeninaAnneGabuten我很抱歉,我不得不修改代碼,使其工作。過了一段時間我爲PHP編程。 ;-) – arkascha

0

創造物質財富與$製造商的名稱和$ ID

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

現在你可以在子類與訪問

+0

我試圖迴應製造商。它顯示用戶輸入 –

+0

'$ manufacturer'和'$ id'在這裏不是對象,而是屬性。請不要混淆術語來混淆人。 – arkascha

+0

對不起,我輸錯了 –

0

你應該申報postDataManager類和POSTDATA功能,然後使用$this->manufacturer=$_POST['manufacturer'];$manufacturer$id變量和$this->id=$_POST['id'];