PHP 中类似 Javascript 的对象?

发布于 2024-10-07 11:45:49 字数 216 浏览 2 评论 0 原文

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

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

然后像这样使用它们:

test.foo.bar
test.bar2

在 PHP 中是否有类似的东西而不需要声明类?

It's pretty handy in JS to create objects like this:

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

and then use them like:

test.foo.bar
test.bar2

Is there anything like this in PHP without declaring classes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

长发绾君心 2024-10-14 11:45:49

它称为关联数组。

示例(注意:缩进用于布局目的):

$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 中的 {} 相同)

It's called associative arrays.

Example (note: the indentation is for layout purposes):

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

This is equivalent to the following Javascript code:

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

As an alternative, you can use the pre-declared StdClass.

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

which would be written in JavaScript as:

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

(note: new Object is the same as {} in Javascript)

拔了角的鹿 2024-10-14 11:45:49

stdClass 允许您创建(本质上)无类型对象。例如:

$object = (object) array(
    'name' => 'Trevor',
    'age' => 42
);

如此处所示,创建 stdClass 对象的最快方法是转换关联数组。对于多个级别,您只需在内部再次执行相同的操作,如下所示:

$object = (object) array(
    'name' => 'Trevor',
    'age' => '42',
    'car' => (object) array(
        'make' => 'Mini Cooper',
        'model' => 'S',
        'year' => 2010
     )
);

另一种方法是随后使用递归函数将关联数组转换为对象。这是一个例子。

function toObject(array $array) {
    $array = (object) $array;
    foreach ($array as &$value)
        if (is_array($value))
            $value = toObject($value);

    return $array;
}
// usage:
$array = // some big hierarchical associative array...
$array = toObject($array);

当您不是创建关联数组的人时,这非常有用。

不幸的是,即使 PHP 5.3 支持匿名方法,您也不能将匿名方法放入 stdClass 中(尽管您可以将匿名方法放入关联数组中)。但这还不算太糟糕。如果你想要其中的功能,你真的应该创建一个类。

stdClass allows you to create (essentially) typeless objects. For example:

$object = (object) array(
    'name' => 'Trevor',
    'age' => 42
);

As shown here, the fastest way to create a stdClass object is to cast an associative array. For multiple levels, you just do the same thing again inside like this:

$object = (object) array(
    'name' => 'Trevor',
    'age' => '42',
    'car' => (object) array(
        'make' => 'Mini Cooper',
        'model' => 'S',
        'year' => 2010
     )
);

Another method is to convert the associative array to an object afterwards with a recursive function. Here's an example.

function toObject(array $array) {
    $array = (object) $array;
    foreach ($array as &$value)
        if (is_array($value))
            $value = toObject($value);

    return $array;
}
// usage:
$array = // some big hierarchical associative array...
$array = toObject($array);

This is useful when you're not the one making the associative array.

Unfortunately, even though PHP 5.3 supports anonymous methods, you cannot put an anonymous method into a stdClass (though you can put one into an associative array). But this isn't too bad anyway; if you want functionality in it, you really should create a class instead.

塔塔猫 2024-10-14 11:45:49

您可以使用 php 中包含的 StdClass 对象或 ArrayObject(尽管后者要求您安装了 SPL)。不过,除非您需要使用 -> 运算符专门访问这些值,否则使用关联数组会更有效。

You can use a StdClass object or an ArrayObject which are included in php (though the latter requires that you have SPL installed). Though unless you need to access the values specifically with the -> operator its more efficient to just use an associative array instead.

·深蓝 2024-10-14 11:45:49

我认为您正在寻找的是关联数组

$test["foo"]["bar"]

http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=keyed+arrays

I think what you are looking for is an Associative Array

$test["foo"]["bar"]

http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=keyed+arrays

笑叹一世浮沉 2024-10-14 11:45:49

最接近的东西是数组。

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

echo $test['foo']['bar'];

The closest thing would be arrays.

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

echo $test['foo']['bar'];
无所谓啦 2024-10-14 11:45:49

从技术上来说,不。但是,如果您正在创建一个数据对象(即没有方法),那么从技术上讲您可以编写一个 JSON 字符串并使用,

$obj = json_decode($obj_string);

但我不推荐它。我认为会有显着的速度损失。

编辑
尽管不言而喻,但应该使用关联数组而不是平面数据对象。

Technically, no. However if you are creating a data object (ie no methods), you could technically write a JSON string and use

$obj = json_decode($obj_string);

I wouldn't recommend it however. I assume there would be significant speed loss.

EDIT
Though it goes without mentioning, associative arrays should be used for this instead of flat data objects.

凡尘雨 2024-10-14 11:45:49

这样做的唯一原因是如果您希望使用 JSON 将数据传回 JavaScript 函数。在这种情况下,请在数组上使用 json_encode。否则,只需将其保留为数组,因为没有理由对其进行编码然后解码,使其看起来像 JavaScript。

The only reason to do that is if you wish to pass data back to a JavaScript function with JSON. In that case, use json_encode on the array. Otherwise, just keep it as an array, as there's not reason to encode it and then decode it just so it looks like JavaScript.

落花随流水 2024-10-14 11:45:49

尝试这样: https://github.com/ptrofimov/jslikeobject

作者实现了类似 JS 的对象,你甚至可以通过 $this 指针访问函数的属性。

但也许用这样的物体来代替通常的物体并不是那么好。

Try this way: https://github.com/ptrofimov/jslikeobject

Author implemented JS-like objects, you can even access properties from functions via $this pointer.

But perhaps it is not so good to use such objects instead of usual ones.

神仙妹妹 2024-10-14 11:45:49
$a = array(
'a'=> 123,
'b'=> 334,
'c'=> 7853
 );
echo json_encode($a);

结果如下:{"a":123,"b":334,"c":7853}

$a = array(
'a'=> 123,
'b'=> 334,
'c'=> 7853
 );
echo json_encode($a);

This will be the result: {"a":123,"b":334,"c":7853}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文