Nick Anderegg
Nick Anderegg

Reputation: 1016

Should an array or a class be used for holding multiple variables in PHP?

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 */

Upvotes: 2

Views: 1098

Answers (7)

user895378
user895378

Reputation:

  1. 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 new object.

  2. 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.

  3. 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 __get and __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.

Upvotes: 3

Steve
Steve

Reputation: 642

Arrays are better if you're only coding a small project without many functions. However, classes have their advantages. For example, would you rather type

$class->db_update("string", $database);

or

$query = "SELECT * FROM `table` WHERE foo='".$array['bar'].'";
mysql_connect("...
mysql_query($query...

Basically, each side has its advantages. I'd recommend the OOP way as most other people here should and would.

EDIT: Also, take a look at this.

Upvotes: 0

Jerome WAGNER
Jerome WAGNER

Reputation: 22422

The 3 options are valid but with a different degree of encapsulation/protection from the outside world.

from lowest protection to highest :

  1. array
  2. object with direct access to public properties
  3. object with getter/setters

The choice highly depends on the environment of your project (2 hours ? sent to the bin tomorrow ?)

choice 2 seems pragmatic.

take into account that depending on your database wrapper, the data could be fetched into array or objects. If it is fetched as an array, you may have to map those to objects.

Upvotes: 1

elvispt
elvispt

Reputation: 4942

I would go with the class, with the properties being private.

Any operations pertaining to the student information could/should be created in that class.

If this was a one time thing, I would go for the array, but really, I know what it means to have something that is going to used one time only and then finding out that I need to execute n operations on the data, and end up having to go for a class.

Upvotes: 0

Janus Troelsen
Janus Troelsen

Reputation: 21300

Regarding your performance question, classes are probably faster than arrays, since different instances are stored independently. By putting all your stuff in one giant hash-map (associative array), you are also getting some of the limitations/properties of arrays. For example, ordering. You don't need that. Also, if the PHP interpreter isn't being smart, it will hash your lookup strings each time you lookup. Using classes and static typing that wouldn't be necessary.

Upvotes: 1

Surreal Dreams
Surreal Dreams

Reputation: 26380

You could create a class for a single student, with appropriate operations for a single student, like updating grades or getting a full name (private data members with functions for access). Then create another class for multiple students that contains an array of single students. You can create functions that operate on sets of students, testing and calling the individual student functions as needed.

The high level answer is that you can do this any of the ways you suggest, but most of us will recommend the OOP solution. If your needs are very simple, a simple array may suffice. If your needs change, you may have to re-code the whole thing for objects anyway. Classes can be kept simple too, so I suggest you start with classes and add complexity as needed. I believe that long term, it will maintain and scale better built with classes.

Upvotes: 3

Johannes Klauß
Johannes Klauß

Reputation: 11020

This is a subjective question with no definitive answer but I would recommend the OOP way. You could create a class Parser holding an instance of StudentInformation.

It's way more comfortable and you can add more methods if you need some additional processing.

Upvotes: 0

Related Questions