How to Build Better PHP Object Arrays, Similar to C# Object Lists

One of the problems I have with PHP is that building lists of objects and being able to access object properties can be a bit tricky. Of course, there’s the tried-and-true method of creating an associative array, encoding it, and then using your IDE to type-hint the object as needed. But, who wants to rely on the IDE to tell types?

In C# you can build objects into a List like we see in the following example:

class Car
{
public string Make { get; set; }
public string Model { get; set; }
}

List<Car> cars = new List<Car>();

var car1 = new Car() { Make = "Chevy", Model = "Silverado" };
cars.Add(car1);

The classic way of doing this in PHP is to build an associative array and then push it into an existing array, like this:

$cars = [];
$car1 = [];
$car1["Make"] = "Chevy";
$car1["Model"] = "Silverado";
array_push($cars, $car1);
You can then typehint using your IDE (JetBrains does this, I know) by using the following syntax:
$data = [
[
'Make' => 'Chevy',
'Model' => 'Silverado'
]
];
$data = json_encode($data);
$cars = json_decode($data);

/** @var $car /Some/Namespace/Car */
foreach ($cars as $car)
{
// You'll be able to get intellisense when you do:
echo $car->Make;
}

When using the IDE type-hint you’ll be able to access intellisense on your object type. To me, this feels really gross. Not the IDE type-hint, but the associative array aspect.

To accomplish this a “better” way you can instead make an object and then build up that object and add it to an array, like this:

class Car
{
public $Make;
public $Model;

public function __construct(string $make, string $model)
{
$this->Make = $make;
$this->Model = $model;
}
}
$cars = [];
$car1 = new Car("Chevy", "Silverado");
$car2 = new Car("Toyota", "Camry");
array_push($cars, $car1);
array_push($cars, $car2);
foreach ($cars as $car)
{
echo $car->Make . "\n";
}

Notice in the foreach loop at the end that we get to take advantage of an actual object property $car->Make instead of using an associative array pointer like this: $car[“Make”]

It’s a simple workaround that makes using your IDE and development tools more powerful. And it makes it so that your return data is actually backed by an object. Instead of constantly building up an associative array each time you return some data and taking the risk of one of those being a different shape than another.

It’s important to not that in PHP you can access a JSON decoded string just like a PHP object, with the $objName->Property skinny arrow notation. If you were to simply access an item from an associative array you must use the bracket notation like this: $arrayItem[“property”] and it cannot be accessed like an object.

Hopefully you got something out of this!

Leave a Reply

Your email address will not be published. Required fields are marked *