Arrays or objects in PHP?
I assumed until a couple of days ago that objects are way better then arrays, but let’s take a closer look into that.
As objects are an instance of a class you can always know what type of data is inserted in the object, when trying this in an array you quickly get in to problems, for example:
$testcase = array(); $testcase["Name"] = "testcase"; $testcase["value"] = 20;
When doing this in objects, you can split it up very easy like so:
$testcase = new testcaseObject(); $testcase->setName("testcase"); $testcase->setValue(20);
I guess you see my point….
When using huge amount of data though, arrays seem to have the upper hand in memory usage so that can count as an advantage.
When we create a query to get some data from a database that returns us multiple rows, the best thing you can do is make an array of objects. Like this:
while( statement ) { $id = $row->categoryId; // If category doesn't exist, we create him, else do nothing if (!isset($category[$id])) { $category[$id] = new testcaseCategory (); $category[$id]->setId($id); $category[$id]->setName($queryrow[categoryName]); } // Create testcaseObject $testcase = new testcaseObject(); $testcase->setId($queryrow[id]); $testcase->setValue($queryrow[name]); // Add testcaseObject to testcaseCategory. $category[$id]->addTestCaseObject($testcase); }
Have fun with it.
Comments