Currently, I am creating a script that will parse information out of a certain type of report that it is passed to it. There is a part of the script that will pull a students information from the report and save it for later processing.
Is it best the hold it in the form of a class, or in an array variable? I figure there are 3 methods that I could use.
EDIT: Really, the question comes down to does any one way have any sort of performance advantage? Because otherwise, each method is really the same as the last.
As a class with direct access to variables:
class StudentInformation {
public $studentID;
public $firstName;
public $lastName;
public $middleName;
public $programYear;
public $timeGenerated;
function StudentInformation(){}
}
As a class with functions:
class StudentInformation {
private $studentID;
private $firstName;
private $lastName;
private $middleName;
private $programYear;
private $timeGenerated;
function StudentInformation(){}
public function setStudentID($id)
{
$this->studentID = $id;
}
public function getStudentID()
{
return $this->studentID;
}
public function setFirstName($fn)
{
$this->firstName = $fn;
}
/* etc, etc, etc */
}
Or as an array with strings as keys:
$studentInfo = array();
$studentInfo["idnumber"] = $whatever;
$studentInfo["firstname"] = $whatever;
$studentInfo["lastname"] = $whatever;
/* etc, etc, etc */
Trying to optimize the use of an array vs. a simple value object is probably an unnecessary micro-optimization. For the simplest cases, an array is faster because you don’t have the overhead of constructing a
newobject.It’s important to remember this: array is NOT the only data structure that exists. If you don’t need the hash capabilities, a simple
SplFixedArraydocs will result in lower memory overhead and faster iteration once you get past the initial overhead of object creation. If you’re storing a large amount of data the aforementioned fixed array or one of the other SPL data structures are likely a better option.Finally: value objects should be immutable, so in your case I would strongly recommend the encapsulation afforded by an object over the ability to assign hash map values willy-nilly. If you want the simplicity of using the array notation, have your class implement
ArrayAccessdocs and get the best of both worlds. Some would suggest magic getters and setters with__getand__set. I would not, as magic generally obfuscates your code unnecessarily. If you really really need magic, you might reconsider your design.There’s a reason why the OOP paradigm is recognized as the best programming paradigm that we’ve come up with — because it’s the best paradigm we’ve come up with. You should use it. Avoid falling into the trap of many/most PHP devs who use arrays for everything.