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开发者_如何学JAVA 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
- If you 'free' the Food() object at the end of the loop, you'd be killing the last reference to it you pushed into $FoodArray as well. PHP will clean up for you and delete things when they go out of scope. Since you're assigning to a global array, the scope is the whole script. So unless you explicitly take steps to delete an item from $FoodArray, the objects will be kept around until the script exits.
- http://www.php.net/manual/en/language.oop5.references.php
- array_push puts elements onto the end of the array, so they'll get an incrementing index number.
Try the following
$FoodArray = array();
$DrinkArray = array();
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
$FoodArray[] = $FoodObj;
unset($FoodObj);
}
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.
精彩评论