Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can we use $_POST variable in a class

Tags:

php

I was just learning class in PHP and so I am messing around with it. I just tried to get a value from a user and display it using a class. However, when I tried to use $_POST variable inside the class it shows an error.

Here is the code:

<form action="classess.php" method="POST" >
<b>Enter the rate : </b>
<input type="text" name="price" />
<input name="submit" type="submit" value="Click" />
</form>
<?php

class rating
{
  public $rate = $_POST['price'];
  public function Display()
  {
    echo $this -> rate;
  }
}

$alex = new rating;
$alex ->Display();
?>
like image 899
wek Avatar asked Nov 29 '22 15:11

wek


1 Answers

You cannot have statements inside of property definitions. Use a constructor instead:

class Rating {
    public $rate;

    public function __construct($price) {
        $this->$rate = $price;
    }

    public function display() {
        echo $this->rate;
    }
}

$alex = new Rating($_POST['price']);
$alex->display();

Some points:

  • Don't make it hard on yourself. If you need something to make the class work, ask it in the constructor.
  • ClassNames are usually written in CapitalCase, and methodNames are written in camelCase.
  • It might be preferable for the display() function to actually return the rate, instead of echoing it. You can do more stuff with a returned value.
like image 146
Madara's Ghost Avatar answered Dec 06 '22 00:12

Madara's Ghost