HTML Code:
<form action="tree.php" method="post" accept-charset="utf-8">
<select name="type">
<option selected="selected" disabled="disabled">Select Type</option>
<option value="Orange">Orange</option>
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
</select>
<p><input type="submit" value="Continue →" name="treetype"></p>
</form>
Tree.php
PHP Code:
<form action="" method="post" accept-charset="utf-8">
<select name="command">
<option selected="selected" disabled="disabled">Commands</option>
<option value="oneYearPasses">Grow one year</option>
<option value="count_fruits">Count the fruits</option>
</select>
<p><input type="submit" value="Continue →" name="commands"></p>
</form>
<?php
include('class_tree.php'); ## includes the class
$Tree = new Tree;
$TreeType = $_POST['type'];
if(isset($_POST['treetype'])){
echo $Tree->setType($TreeType);
}
if($_POST['command'] == 'oneYearPasses'){
echo $Tree->oneYearPasses();
}
elseif($_POST['command'] == 'count_fruits'){
echo $Tree->count_fruits();
}
?>
class_tree.php
PHP Code:
<?php
class Tree{
private $Type;
private $Height = 1;
private $Fruit = 0;
# Sets the type of Tree
public function setType($TheType){
$this->Type = $TheType;
$return_val = '<b>'.$TheType.' tree has been cultivated.</b><br/>';
return $return_val;
}
# When oneYearPasses is called, the function adds 1 meter to the height.
# When the height reaches 10, it grows 10 fruits.
# When the tree grows to 10 meter, every year it grows 5 fruits.
# When the tree reaches height of 15 meters, it dies.
public function oneYearPasses(){
$TheHeight = $this->Height++;
$return_val = 'The '.$this->Type.' Tree grows to '.$TheHeight.' meter <br/>';
if($TheHeight == 10){
$return_val = 'The '.$this->Type.' Tree grows to '.$TheHeight.' meter <br/>';
$return_val .= '<b>Your Tree is now mature and grows 10 fruits</b><br/>';
$this->Fruit = 10;
}
if($TheHeight > 10){
$return_val = 'The '.$this->Type.' Tree grows to '.$TheHeight.' meter <br/>';
$return_val .= '<b>The Tree grows more 5 fruits</b><br/>';
$this->Fruit += 5;
}
if($TheHeight == 15){
$return_val = '<b>Sorry but your tree died</b><br/>';
$this->Fruit = 0;
}
return $return_val;
}
# Counts the number of $this->Fruit present in $this->Tree
public function count_fruits(){
$return_val = 'The '.$this->Type.' Tree has grown '.$this->Fruit.' Fruits';
return $return_val;
}
}
?>
The oneYearPasses function doesn't take the setType into the account and just echo out 'Tree grows to 1 meter'. How would I fix it?
PHP Code:
if($_POST['command'] == 'oneYearPasses'){
echo $Tree->oneYearPasses();
}
elseif($_POST['command'] == 'count_fruits'){
echo $Tree->count_fruits();
}
And for those who prefer clean code, please check my code and let me know what can I do to improve my code.