Skip to content
Advertisement

How to create javascript like object in php

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

JavaScript

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:

JavaScript

You then access elements using square brackets:

JavaScript

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:

JavaScript

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

JavaScript

And use it like this:

JavaScript

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