【问题标题】:why do I get an error of undefined variable when I define it in the constructor of the class?为什么在类的构造函数中定义变量时会出现未定义变量的错误?
【发布时间】:2013-03-15 09:41:08
【问题描述】:

来自以下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

为什么会这样?

【问题讨论】:

  • 您使用的变量可能尚未在构造函数中设置为值。

标签: php oop class


【解决方案1】:

在类内部,您必须使用$this-&gt; 引用您的成员属性,例如

<?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']

【讨论】:

  • 解释“没有帮助”?注意它必须是$this-&gt;text_field 而不是$this-&gt;$text_field。并检查是否设置了$_POST['text_field']
  • $this->$text_field 更改为 $this->text_field 解决了我的问题,非常感谢。
【解决方案2】:

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

例如,不能是这样的

$this->$text_field;

这是正确的方法

$this->text_field;

【讨论】:

    【解决方案3】:

    应该是-

    echo $this->text_field;
    

    在您的 print_data 方法以及所有其他方法中...

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

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 1970-01-01
      相关资源
      最近更新 更多