When to use objects instead of arrays?

In PHP you can use arrays as parameters to pass data. But isn’t it better to use an object? The problem with arrays is that we can not force the structure. An array can have any number of values and we can’t tell the outside world what the correct structure is. Well we can be documenting it, but that’s not good. Code should need to be clear without much documentation. So we should try to enforce the data structure of parameters that we pass.

Flexible arrays

So one of the reasons that we use arrays is because its very flexible. Its easy to use and also the first thing that comes to mind. We use this as a hack to use the least amount of function arguments as possible. Instead of 10 arguments, we just create 1 with an array of all 10. This is in my opinion just moving the issue. And while before we had the ability to force the structure, now we moved it to an array, we lost that ability.

An example with arrays

<?php
/**
 * @param int $id
 * @param array $settings
 */
public function showInput($id, array $settings)
{
  // The code
}

showInput('inputId', [
    'name' => 'Name',
    'value' => 'Jeffrey Verreckt',
    'classes' => ['required', 'input-large'],
]);

Enforcing structure with objects

When you create an object you then can enforce the structure. In your constructor you can force the required parameters and your IDE will tell you what kind of values to expect. You can then add optional parameters trough setters. This will require more time to set up then an array. But it will allow you think more about your structure and will make it easier in the future. You will need to consider that other developers might be using your classes and methods. And this will make it easier for them to implement your code. If you are creating libraries for external developers, then this is even more important. But don’t overuse this. You need to think when to create objects and when not. For pure private methods and data passing this might be an overkill and then we can just use arrays.

An example using objects

/**
 * Class InputSettings
 */
class InputSettings
{
    /**
     * @var string
     */
    private $name;
    /**
     * @var string
     */
    private $label;
    /**
     * @var string
     */
    private $value;
    /**
     * @var array
     */
    private $classes;

    /**
     * InputSettings constructor.
     * We place required parameters in constructor
     * @param string $name
     * @param string $label
     * @param string $value
     */
    public function __construct($name, $label, $value)
    {
        $this->name = $name;
        $this->label = $label;
        $this->value = $value;
    }

    /* Getters and settings here */
}

/**
 * @param $id
 * @param InputSettings $settings
 */
public function showInput($id, InputSettings $settings)
{
  // Code here
}

$settings = new InputSettings('name', 'Name', 'Jeffrey Verreckt');
$settings->setClasses(['required', 'input-large']);
showInput('inputId', $settings);

Always use objects

If you want to truly create object oriented code. Then we should try to always use objects instead of arrays. Data from the database should come as an object. You should return objects to other classes. This will also create additional type safety. The exception is when passing data between private methods. Then its sometimes wiser to use arrays. Also when creating a collection of objects, then you need to just use a simple array of your objects.

The downside of using objects is that you require to create more error handling. Well is this a downside? With arrays you cant handle errors or force structure. But with objects you can. But implementing this might cost more time. But isn’t more safety a good thing? We should think about the future. Which structure gives us the most flexibility and least issues in the future. Which is the clean and best solution?

But what about JSON returns?

You can also return objects instead of arrays. You could pass a array with error or success and then some success or error message. But isn’t it better to return an object of your successful data? And in case there is an error to return exceptions? Well I think it is and this is something you will also need to consider.

Conclusion

You should always consider the scaling needs of your codeĀ and consider that a structured array might be a quick fix, but an object is a much more resilient and scale able solution. Like always you should think to code.