Im new to PHP and would like to get some advice on the following situation:
I have a file in which Im parse an XML file. My strategy has been create a “parser.php” file. Then create separate files for each tag in the XML file. Each of these separate files is a class that when instantiated will store all the attributes of that particular tag.
I have several loops in the parser that instantiate the class that corresponds with the tag when they encounter it.Once the loop is done that object is then inserted into a global array.
Here is the code:
<?php
include ('class.Food.php');
include ('class.Drink.php');
$xml = simplexml_load_file("serializedData.xml");
//Global Variables==============================================================
$FoodArray = array();
$DrinkArray = array();
$FoodObj;
$DrinkObj;
foreach($xml->children() as $child)
{
//Instantiate a Food object here and insert into the array
$FoodObj = new Food();
//Add attributes of tag to the Food object
array_push($FoodArray, $FoodObj);
}
Thus at the end of each loop there would be a food object created and that would be added to the FoodArray.
My questions are:
- Do I have to explicitly call a destructor or free the object memory at the end of the loop?
- Using the above syntax, will the FoodObj be stored in the FoodArray as a reference or a value
- Each time the variable Food gets a different instance stored in it, does that matter when stored in the array? All the objects stored in the array go by the index number right?
Thanks
Try the following
1) unset’ng the instance manually is good form, but unnecessary. the php garbage collector will do it for you anyways and is very efficient.
2) in the example above, $FoodArray[i] will continue to point to the instance even after $FoodObj is unset.
3) it works whether $FoodObj is local to the loop or not. But for best practice it should be.