0

I have the following data structure. I need an array of movies. Each movie has a title, rating and year.

Movies:

--Title = "The Hobbit";
--Rating = 7;
--Year   = 2012;

--Title = "Lord of the rings";
--Rating = 5;
--Year   = 2001;

If this was JavaScript you would have an array of objects:

const movies = [{
  title:"The Hobbit",
  rating:7,
  year:2012
},
{
  title:"Lord of the rings",
  rating:5,
  year:2001
}]

How do you model this in PHP? I know that you could create a class of Movie and each movie would be an instance of this class, but is this required? Can you just have non-class objects like with JavaScript?

2

2 Answers 2

2

There are two ways:

Associative arrays:

$movies = [
[
  "title" => "The Hobbit",
  "rating" => 7,
  "year" => 2012
],
[
"title" => "Lord of the rings",
  "rating" => 5,
  "year" => 2001
]
];

Or you use an object of type \stdClass. Easiest definition:

$movie1 = (object)[
  "title" => "The Hobbit",
  "rating" => 7,
  "year" => 2012
];

Or you do it this way:

$movie1 = new \stdClass();
$movie1->title = "The Hobbit";

Access works like that:

echo $movie1->title; // The Hobbit

You can collect them again in $movies:

$movies = [$movie1];
Sign up to request clarification or add additional context in comments.

Comments

0

You absolutely can! Objects extend a base \stdClass which would behave similarly to your description. A great example of this is the json_decode() method defaults.

To create one of these objects from scratch, either invoke the \stdClass constructor, or just typecast an array to (object).

Based on your example JSON, here's the use of a \stdClass in PHP, both from serialisation and instantiating your own objects.

<?php

$decoded = json_decode('[{
        "title": "The Hobbit",
        "rating": 7,
        "year": 2012
    },
    {
        "title": "Lord of the rings",
        "rating": 5,
        "year": 2001
    }
]');
print_r($decoded);
echo $decoded[0]->title . PHP_EOL;

print_r(new \stdClass());
print_r((object)[]);
print_r((object)['example_public_property' => 'example_value']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.