2013-03-15 116 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关键字来访问成员属性和函数。

相关问题