php - PHP 中类似 Javascript 的对象?

标签 php javascript object

在 JS 中创建这样的对象非常方便:

test = { foo : { bar : "hello world" }, bar2 : "hello world 2" }

然后像这样使用它们:

test.foo.bar
test.bar2

在没有声明类的情况下,PHP 中有类似的东西吗?

最佳答案

它叫做关联数组。

示例(注意:缩进是为了布局目的):

$test = array(
  'foo' => array(
     'bar' => 'hello world'
   ),
  'bar2' => 'hello world 2'
);
$test['foo']['bar'];
$test['bar2'];

这等同于以下 Javascript 代码:

var test = {
  'foo': {
    'bar': 'hello world',
  },
  'bar2': 'hello world 2'
};

作为替代方案,您可以使用预先声明的 StdClass。

$test = new StdClass;
$test->foo = new StdClass;
$test->foo->bar = 'hello world';
$test->bar2 = 'hello world 2';

用 JavaScript 写成:

var test = new Object;
test.foo = new Object;
test.foo.bar = 'hello world';
test.bar2 = 'hello world 2';

(注意:new Object 与 Javascript 中的 {} 相同)

关于php - PHP 中类似 Javascript 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4401623/

相关文章:

javascript - 除了 Mozilla Firefox 之外,视频不会在任何浏览器中自动播放

javascript - 如何获取 JS 中 YYYY-MM-DD 格式的第二天日期?

javascript - Js if语句不能正常工作

javascript - Noob jQuery "$"函数返回问题

php - 通过 AJAX 插入 PHP PDO

javascript - 发布请求抛出 net::ERR_HTTP2_PROTOCOL_ERROR

php - 将查询结果保存在一个数组中

php - MVC : how to ajax?

javascript - Javascript 中的 API 客户端

Java 目标/选择类/对象 - 困惑(抱歉标题不好)