how can we use $_POST variable in a class
php
Solution
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 `echo`ing it. You can do more stuff with a returned value.
Problem
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(); ?> ```