Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

php - 您可以像使用JavaScript等一样在PHP中具有非类对象吗?(Can you have non class objects in PHP as you can with JavaScript etc?)

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:

(如果这是JavaScript,则将有一个对象数组:)

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?

(您如何在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?

(我知道您可以创建一个Movie类,每个电影都是该类的一个实例,但这是必需的吗?)

Can you just have non-class objects like with JavaScript?

(您是否可以像JavaScript那样拥有非类对象?)

  ask by Evanss translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(或者,您使用\ 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中再次收集它们:)

$movies = [$movie1];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...