saplingPro
saplingPro

Reputation: 21329

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 ?

Upvotes: 5

Views: 5742

Answers (3)

ndarriulat
ndarriulat

Reputation: 859

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;

Upvotes: 12

ShuklaSannidhya
ShuklaSannidhya

Reputation: 8976

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.

Upvotes: 2

Marko D
Marko D

Reputation: 7576

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

Upvotes: 7

Related Questions