当我在类的构造函数中定义未定义的变量时,为什么我得到一个未定义变量的错误


why do I get an error of undefined variable when I define it in the constructor of the class?

从以下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();

我尝试打印从action_script.php的html中发送的数据,但我得到以下警告/错误:

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

我正在使用$this语句,但仍然有同样的问题,然后我发现调用的变量必须没有$符号,正如上面提到的一些用户。

例如不能像这样

$this->$text_field;

这是正确的方式代替:

$this->text_field;

在类内部,你必须使用$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']是否设置在使用它之前

应该是-

echo $this->text_field;

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

使用$this关键字访问成员属性和函数