Calling method on a PHP object which contains an array
I have a PHP class called "food". The internal data structure of the class is an Array.
class Food
{
public $dataArray;// = array();
public $sidesArray;// = array();
public function __construct()
{
$this->dataArray = array();
$this->sidesArray = array();
echo"Created new Food instance<br/>";
}
public function setName($food_Name)
{
$this->dataArray["food_name"] = $food_Name;
}
public function getName()
{
return $this->dataArray["food_name"];
}
When I call this method of the class :
$food_name = $foodItem->getName();
I get this exception:
Fatal error: Call to a member function getName() on a non-object......
However when I call this function on the object:
print_r($foodItem);
I get this output:
Array ( [0] => Food Object ( [dataArray] => Array ( [food_name] => SimpleXMLElement Object ( [0] => Tomato Soup ) [food_Cals] => SimpleXMLElement Object ( [0] => 200 ) [food_Desc] => SimpleXMLElement Object ( [0] => great ) [food_price] => SimpleXMLElement Object ( [0] => 2.00 ) [num_sides] => SimpleXMLElement Object ( [0] => 1 ) ) [sidesArray] => Array ( [0] => Side Object ( [dataArray:private] => Array ( [side_name] => SimpleXMLElement Object ( [0] => mashed potatoes ) [side_Cals] => SimpleXMLElement Object ( ) [side_Category] => SimpleXMLElement Object ( [0] => Sides ) [side_desc] => SimpleXMLElement Object ( ) [side_price] => SimpleXMLElement Object ( [0] => 2.00 ) ) ) ) ) )
My questi开发者_C百科on is why is that method getName() not working? How do I get the "name" out of the foodItem object.
Any help would be greatly appreciated.
Thanks
Looks like $foodItem
is an array of Food
objects.
You will need to loop over the array or reference specific items by index to use the class methods, eg
// loop
foreach ($foodItem as $food) {
echo $food->getName();
}
// direct access
echo $foodItem[0]->getName();
Be careful as you will trigger an E_NOTICE
"undefined index" error if attempting to call Food::getName()
before a name has been set via Food::setName()
.
I'd be inclined to set the name in the constructor
public function __construct($name)
{
$this->dataArray = array('food_name' => $name);
// any other constructor tasks
}
You have to try it that way
$foodItem[0]->getName();
because your object is in $foodItem[0]. Then it will be working. But also a remark:
- if you make a set/get method you should make $dataArray private. If not you can access it directly. That's not a proper oop.
精彩评论