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();
?>
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();
ClassNames
are usually written in CapitalCase, and methodNames
are written in camelCase. display()
function to actually return
the rate, instead of echo
ing it. You can do more stuff with a returned value.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With