2

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 */
4
  • 5
    Array Oriented Programming! Yippieeee! Commented Jun 5, 2012 at 19:21
  • I edited the question. Mainly what I'm asking is, does any one method have an advantage to another, or are they all really just different solutions to the same problem. Commented Jun 5, 2012 at 19:27
  • I'm too lazy to write out an answer right now, but this seems more like a question of, "What are the benefits of object oriented programming?" ... you might try just googling that. Commented Jun 5, 2012 at 19:35
  • Haha, I know the benefits of object oriented programming. It's just that I've been using only C++ and Java for the past year, and now that I'm back in PHP, I miss struct. The class with no getters/setters is most like struct, but I think I'll use getters/setters in case I need to add functionality at some point. Commented Jun 5, 2012 at 19:38

8 Answers 8

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

If you want to build out getters and setters very easily in PHP, look up magic methods, specifically __call(). You make one slick function that handles getting any data member and a second to set any data member. Add in a whitelist of allowed members and you're done. Nice to have when there are more than two or three members, or you might add 20 or 30 more someday.
1

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.

Comments

1

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.

Comments

0

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.

Comments

0

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.

Comments

0

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.

2 Comments

I hope he types neither. Example #1 looks like an active record, which is bad. Example #2 uses (soon to be) deprecated mysql_ functions, which is really bad (use PDO or mysqli instead).
@webbiedave It was an example. I did not mean for him to use either, I just thought of some random functions that could be used this way.
0

Pro of Array

  • PHP was built thinking in Array, so Array is a first-class citizen while classes are not. Example: many functions only work with arrays, and in some cases work with array and generic classes (ex, json_encode, and json_decode, PDO, etc.).

  • In other languages, you can create a field of a list of an object.

class SomeClass {
    public List<OtherClass> fields;
}
  • PHP doesn't have it, so it relies on a generic array, and it's up to the developer to determine the type of data stored here.
class Someclass {
    public array $fields;
}

Pro of Classes

  • Array does not allow functions

  • When you copy an array, then you create a new variable. When you copy an object, then you create an instance of it.

  • Classes have more functionalities than arrays other than store information.

<?php
$a1=["field"=>1];
$a2=new stdclass();
$a2->field=1;
echo "pre:";
var_dump($a1); // 1
var_dump($a2); // 1
$a1copy=$a1;
$a1copy['field']=2;
$a2instance=$a2;
$a2->field=2;
echo "post:";
var_dump($a1); // 1 ($a1 and $a1copy are different variables)
var_dump($a2); // 2 ($a2 and $a2instance share the same memory)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.