Reputation: 294
I'm extremely new to php so excuse my code if you think it is a mess but I've been trying to figure this out for hours.
I am trying to use the getter and setter method to pull functionality from a class then use an array to create new objects based off the class. $_GET
is to get the input foodNumber
from a HTML form which determines which position in the array is chosen. So if 0 is inputted on the form, it represents Salad
, if 2 is entered on the form it should mean Vegetables
.
So in my mind, the $foodObject
is creating a new object from the class FoodArray
. I am trying to make the objects be in an array, so in this case $foodArray
. But I don't know how to input values through an array using the getter setter method using the class functions or how to call them.
Thanks in advance!
<?php
class FoodArray {
private $foodValue;
public function setFoodValue($x){
$this->foodValue=$x;
}
public function getFoodValue(){
return $this->foodValue;
}
}
$foodNumber = $_GET['foodNumber'];
$foodObject = new FoodArray;
$foodArray = array ("Salad", "Vegetables", "Pasta", "Pizza", "Burgers");
$foodArray=$foodObject->getFoodValue();
echo "The number you chose is ". $foodNumber;
echo "The food item you choose is".$foodArray[$foodNumber];
?>
/////HTML FORM/////
<html>
<body>
<form action="class_with_getter_and_setter.php" method="get">
<b>Choose a number between 0-4 and get a mystery food!</b>
<input type="text" name="foodNumber">
<input type="submit">
</form>
</body>
</html>
Upvotes: 0
Views: 1788
Reputation: 2149
I'm not exactly sure what your final intention is but I can try to point out a couple of places where you are going wrong:
setFoodValue()
method of the FoodArray
object is never called so $foodValue
has no value$foodArray
is set as an array but is immediately overwritten when you call the line $foodObject->getFoodValue()
$foodObject->getFoodValue()
actually returns nothing because $foodValue
was never setThere should be no difference in your getters and setters if you are passing an array or a string you could pass them and retrieve them the same way.
Again not sure exactly what you are trying to accomplish but you could try something like this:
$foodObject = new FoodArray;
$foodArray = array ("Salad", "Vegetables", "Pasta", "Pizza", "Burgers");
$foodObject->setFoodValue($foodArray);
$foodObjectArray = $foodObject->getFoodValue();
echo "The number you chose is ". $foodNumber;
echo "The food item you choose is".$foodObjectArray[$foodNumber];
Upvotes: 1
Reputation: 51
If the problem is that echo "The food item you choose is".$foodArray[$foodnumber];
doesn't produce what you expect, there are two potential problems:
$foodObject
. However, the $foodArray=$foodObject->getFoodValue();
may be messing it up, unless the internal $foodValue
property is (like) the $foodArray
you declare with Salad, Vegetables, etc.$foodArray[$foodnumber]
, the 'n' in number is lowercase where above you set $foodNumber
(capital 'N')Upvotes: 0