php 在php中创建匿名对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6384431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:12:24  来源:igfitidea点击:

Creating anonymous objects in php

phpoopobject

提问by Sujit Agarwal

As we know, creating anonymous objects in JavaScript is easy, like the code below:

众所周知,在 JavaScript 中创建匿名对象很容易,就像下面的代码:

var object = { 
    p : "value", 
    p1 : [ "john", "johnny" ]
};

alert(object.p1[1]);

Output:

输出:

an alert is raised with value "johnny"

Can this same technique be applied in PHP? Can we create anonymous objects in PHP?

可以在 PHP 中应用相同的技术吗?我们可以在 PHP 中创建匿名对象吗?

采纳答案by Rizier123

It has been some years, but I think I need to keep the information up to date!

已经有些年头了,但我想我需要让信息保持最新!

Since PHP 7 it has been possible to create anonymous classes, so you're able to do things like this:

从 PHP 7 开始,可以创建匿名类,因此您可以执行以下操作:

<?php

    class Foo {}
    $child = new class extends Foo {};

    var_dump($child instanceof Foo); // true

?>

You can read more about this in the manual

您可以在手册中阅读有关此内容的更多信息

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.

但我不知道它与 JavaScript 的实现有多相似,因此 JavaScript 和 PHP 中的匿名类之间可能存在一些差异。

回答by Jon

"Anonymous" is not the correct terminology when talking about objects. It would be better to say "object of anonymous type", but this does not apply to PHP.

在谈论对象时,“匿名”不是正确的术语。最好说“匿名类型的对象”,但这不适用于 PHP。

All objects in PHP have a class. The "default" class is stdClass, and you can create objects of it this way:

PHP 中的所有对象都有一个类。“默认”类是stdClass,您可以通过以下方式创建它的对象:

$obj = new stdClass;
$obj->aProperty = 'value';

You can also take advantage of casting an array to an objectfor a more convenient syntax:

您还可以利用将数组转换为对象以获得更方便的语法:

$obj = (object)array('aProperty' => 'value');
print_r($obj);

However, be advised that casting an array to an object is likely to yield "interesting" results for those array keys that are not valid PHP variable names -- for example, here'san answer of mine that shows what happens when keys begin with digits.

但是,请注意,将数组转换为对象可能会为那些不是有效 PHP 变量名的数组键产生“有趣”的结果——例如,是我一个答案,显示了当键以数字开头时会发生什么。

回答by Mihailoff

Yes, it is possible! Using this simple PHP Anonymous Objectclass. How it works:

对的,这是可能的!使用这个简单的PHP 匿名对象类。这个怎么运作:

// define by passing in constructor
$anonim_obj = new AnObj(array(
    "foo" => function() { echo "foo"; }, 
    "bar" => function($bar) { echo $bar; } 
));

$anonim_obj->foo(); // prints "foo"
$anonim_obj->bar("hello, world"); // prints "hello, world"

// define at runtime
$anonim_obj->zoo = function() { echo "zoo"; };
$anonim_obj->zoo(); // prints "zoo"

// mimic self 
$anonim_obj->prop = "abc";
$anonim_obj->propMethod = function() use($anonim_obj) {
    echo $anonim_obj->prop; 
};
$anonim_obj->propMethod(); // prints "abc"

Of course this object is an instance of AnObjclass, so it is not really anonymous, but it makes possible to define methods on the fly, like JavaScript do.

当然,这个对象是AnObj类的一个实例,所以它并不是真正的匿名,但是它可以像 JavaScript 那样动态定义方法。

回答by Zuks

Up until recently this is how I created objects on the fly.

直到最近,这就是我动态创建对象的方式。

$someObj = json_decode("{}");

Then:

然后:

$someObj->someProperty = someValue;

But now I go with:

但现在我选择:

$someObj = (object)[];

Then like before:

然后像以前一样:

$someObj->someProperty = someValue;

Of course if you already know the properties and values you can set them inside as has been mentioned:

当然,如果您已经知道属性和值,您可以将它们设置在里面,如前所述:

$someObj = (object)['prop1' => 'value1','prop2' => 'value2'];

NB: I don't know which versions of PHP this works on so you would need to be mindful of that. But I think the first approach (which is also short if there are no properties to set at construction) should work for all versions that have json_encode/json_decode

注意:我不知道这适用于哪个版本的 PHP,因此您需要注意这一点。但我认为第一种方法(如果在构造时没有要设置的属性也很短)应该适用于所有具有 json_encode/json_decode 的版本

回答by T.Todua

Convert array to object (but this is not recursive to sub-childs):

将数组转换为对象(但这不是递归到子孩子):

$obj = (object)  ['myProp' => 'myVal'];

回答by kba

If you wish to mimic JavaScript, you can create a class Object, and thus get the same behaviour. Of course this isn't quite anonymous anymore, but it will work.

如果你想模仿 JavaScript,你可以创建一个 class Object,从而获得相同的行为。当然,这不再是完全匿名的,但它会起作用。

<?php 
class Object { 
    function __construct( ) { 
        $n = func_num_args( ) ; 
        for ( $i = 0 ; $i < $n ; $i += 2 ) { 
            $this->{func_get_arg($i)} = func_get_arg($i + 1) ; 
        } 
    } 
} 

$o = new Object( 
    'aProperty', 'value', 
    'anotherProperty', array('element 1', 'element 2')) ; 
echo $o->anotherProperty[1];
?>

That will output element 2. This was stolen from a comment on PHP: Classes and Objects.

这将输出元素 2。这是从关于 PHP: Classes and Objects 的评论中窃取的。

回答by miken32

Support for anonymous classeshas been available since PHP 7.0, and is the closest analogue to the JavaScript example provided in the question.

自 PHP 7.0 起就提供了对匿名类的支持,并且与问题中提供的 JavaScript 示例最接近。

<?php
$object = new class {
    var $p = "value";
    var $p1 = ["john", "johnny"];
};

echo $object->p1[1];

The visibility declaration on properties cannot be omitted (I just used varbecause it's shorter than public.)

属性的可见性声明不能省略(我只是使用var它是因为它比public.)

Like JavaScript, you can also define methods for the class:

和 JavaScript 一样,你也可以为类定义方法:

<?php
$object = new class {
    var $p = "value";
    var $p1 = ["john", "johnny"];
    function foo() {return $this->p;}
};

echo $object->foo();

回答by Ivan Ivkovi?

From the PHP documentation, few more examples:

从 PHP 文档中,再举几个例子:

<?php

$obj1 = new \stdClass; // Instantiate stdClass object
$obj2 = new class{}; // Instantiate anonymous class
$obj3 = (object)[]; // Cast empty array to object

var_dump($obj1); // object(stdClass)#1 (0) {}
var_dump($obj2); // object(class@anonymous)#2 (0) {}
var_dump($obj3); // object(stdClass)#3 (0) {}

?>

$obj1 and $obj3 are the same type, but $obj1 !== $obj3. Also, all three will json_encode() to a simple JS object {}:

$obj1 和 $obj3 是相同的类型,但是 $obj1 !== $obj3。此外,所有三个都将 json_encode() 转换为一个简单的 JS 对象 {}:

<?php

echo json_encode([
    new \stdClass,
    new class{},
    (object)[],
]);

?>

Outputs:

输出:

[{},{},{}]

https://www.php.net/manual/en/language.types.object.php

https://www.php.net/manual/en/language.types.object.php

回答by d?lo sürücü

Anoynmus object wiki

Anoynmus 对象 wiki


$object=new class (){


};

回答by symcbean

Can this same technique be applied in case of PHP?

在 PHP 的情况下可以应用相同的技术吗?

No - because javascript uses prototypes/direct declaration of objects - in PHP (and many other OO languages) an object can only be created from a class.

否 - 因为 javascript 使用对象的原型/直接声明 - 在 PHP(和许多其他 OO 语言)中,只能从类创建对象。

So the question becomes - can you create an anonymous class.

所以问题就变成了——你能不能创建一个匿名类。

Again the answer is no - how would you instantiate the class without being able to reference it?

答案是否定的 - 你将如何在不能引用它的情况下实例化该类?