A 5 Minute Window: PHP Arrays to Objects

An experiment.

Here’s 5 minutes on how you can, and some reasons why you would want to, convert PHP structured arrays to objects.

The code is below.

<?php
declare(strict_types=1);

// Hi

// Here's some code that I see often in WordPress projects...

$pages = [
  [
    'id'    => 1,
    'title' => 'Home'
  ],
  [
    'id'    => 2,
    'title' => 'About'
  ],
  [
    'id'    => 3,
    'title' => 'Contact'
  ]
];

// An array of arrays that are "things".

// These are much better expressed as objects.

// And this is a really good first introduction to objects if you don't use them much.

// Let's make a "class" - this is like a template for the "things".

class Post {
    // Each post has a publicly accessible ID and title
    public int $id = 0;
    public string $title = '';

    // We will set these for each thing
}

// Now we have the template, let's make the things.

$posts = [];

$posts[] = new Post();
$posts[0]->id = '123'; // Aha! See, with objects and types, we get help with errors! Nice.
$posts[0]->title = 'Hello World';

// Did you see how the editor helped us? Because it knows what the properties of the things are!

$posts[1] = new Post();
$posts[1]->id = '456';
$posts[1]->title = 'Hello again';

// We can also use types to be even more specific and helpful!