在php中创建匿名对象 [英] Creating anonymous objects in php
问题描述
我们知道,使用JavaScript创建匿名对象很容易,就像下面的代码一样:
As we know, creating anonymous objects in JavaScript is easy, like the code below:
var object = {
p : "value",
p1 : [ "john", "johnny" ]
};
alert(object.p1[1]);
输出:
an alert is raised with value "johnny"
可以在PHP中应用相同的技术吗?我们可以在PHP中创建匿名对象吗?
Can this same technique be applied in PHP? Can we create anonymous objects in PHP?
推荐答案
已经好几年了,但是我认为我需要保持信息的最新状态!
It has been some years, but I think I need to keep the information up to date!
自PHP 7起,便可以创建匿名类,因此您可以执行以下操作:
Since PHP 7 it has been possible to create anonymous classes, so you're able to do things like this:
<?php
class Foo {}
$child = new class extends Foo {};
var_dump($child instanceof Foo); // true
?>
You can read more about this in the manual
但是我不知道它与JavaScript的实现方式有多么相似,因此JavaScript和PHP中的匿名类之间可能会有一些区别.
But I don't know how similar it is implemented to JavaScript, so there may be a few differences between anonymous classes in JavaScript and PHP.
这篇关于在php中创建匿名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!