2013-03-15 56 views
2

從以下html,從文本字段中的數據是由action_script.php服務:當我在類的構造函數中定義它時,爲什麼會得到未定義變量的錯誤?

<form method='post' action='action_script.php'> 
     <input type='text' name='text_field' id='text_field' /> 
     <input type='submit' value='submit' /> 
</form> 

action_script.php包含以下代碼:

<?php 
class Tester { 
    private $text_field; 

    public function __construct() { 
     $text_field = $_POST['text_field']; 
    } 

    public function print_data() { 
     echo $text_field; # LINE NUMBER 10 
    } 
} 

$obj = new Tester(); 
$obj->print_data(); 

我嘗試打印數據發送從html in action_script.php但我得到以下警告/錯誤:

Notice: Undefined variable: text_field in E:\Installed_Apps\xampp\htdocs\php\action_script.php on line 10 

這是爲什麼?

+0

您正在使用的變量可能未被設置爲構造函數中的值。 – William 2013-03-15 09:43:34

回答

4

內部類的,你必須參考使用$this->您的成員屬性,像

<?php 
class Tester { 
    private $text_field; 

    public function __construct() { 
     $this->text_field = $_POST['text_field']; 
    } 

    public function print_data() { 
     echo $this->text_field; # LINE NUMBER 10 
    } 
} 

$obj = new Tester(); 
$obj->print_data(); 

您也應該檢查是否$_POST['text_field']在使用它

+0

它不幫助 – saplingPro 2013-03-15 09:45:39

+2

解釋「不幫助」?支付意見,它必須是'$ this-> text_field'而不是'$ this - > $ text_field'。並檢查是否設置了$ _POST ['text_field']' – 2013-03-15 09:46:54

1

前應設置 -

echo $this->text_field; 

在你的print_data方法和你所有的其他方法...

使用$this關鍵字來訪問成員屬性和函數。

相關問題