简体   繁体   中英

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

From the following html , the data from the text-field is served by 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 contains the following code :

<?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();

I try to print the data sent from the html in action_script.php but I get the following warning/error :

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

Why is that ?

Inside of class you must refer to your member properties using $this-> , like

<?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();

You should also check if $_POST['text_field'] is set before using it

I was using the $this statement but still having the same problem, then I figured out the invoked variable must not have the $ symbol, as some of the users above mentioned.

For instance, it must not be like this:

$this->$text_field;

This is the correct way instead:

$this->text_field;

Should be -

echo $this->text_field;

in your print_data method and also in your all the other methods...

Use $this keyword to access member properties and functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM