Skip to content
Advertisement

How to create javascript like object in php

Let’s say, I have a javascript object array like the following.

    let users = [
        {
            'id' => 1,
            'name' => 'John',
            'amount' => 1000,
        },
        {
            'id' => 2,
            'name' => 'Smith',
            'amount' => 2000,
        },
    ];

Now how do I create the same object in PHP and do CRUD operations?

Note: I know it should be : instead of =>. I just wanted it to look more like PHP.

Advertisement

Answer

The universal key-value data structure in PHP is not an object, it’s an associative array. Your code would look like this:

$users = [
    [
        'id' => 1,
        'name' => 'John',
        'amount' => 1000,
    ],
    [
        'id' => 2,
        'name' => 'Smith',
        'amount' => 2000,
    ],
];

You then access elements using square brackets:

$users[0]['amount'] = 0;
$users[1]['amount'] = 3000;
echo $users[0]['amount'];

While using an object for this may be more familiar to a JS developer, using arrays for ad hoc data will let you use much more of PHP’s built-in functionality, which is designed around associative arrays.


On the other hand, if you actually have the same fields in every object, you should declare a class listing those fields. This will give you better performance, better error handling, clearer code, and the ability to encapsulate logic in those classes in future.

In PHP 8, you can write this using constructor property promotion which looks like this:

class User
{
    public function __construct(
        public int $id,
        public string $name, 
        public int $amount
    ) {}
}

You would then create the array like this (using named parameters, also new in PHP 8.0):

$users = [
    new User(
        id: 1,
        name: 'John',
        amount: 1000,
    ),
    new User(
        id: 2,
        name: 'Smith',
        amount: 2000,
    ),
];

And use it like this:

$users[0]->amount = 0;
$users[1]->amount = 3000;
echo $users[0]->amount;

In older versions of PHP, the code to declare the classes and create the objects would have to be slightly different, but the benefits would be the same.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement