简体   繁体   English

PHP:对象实例上的新运算符创建对象实例。 为什么?

[英]PHP: new operator on an object instance creates an object instance. Why?

What is the reason the following code works and generates the given result. 以下代码的工作原理是什么,并生成给定的结果。 Is it a special language construct that is just supported by PHP? 它是PHP支持的特殊语言构造吗? If so, then which one? 如果是这样,那么哪一个? Or is it just a simple php-ism? 或者它只是一个简单的php-ism?

class Foo {};

$a = new Foo();
$b = new $a();

var_dump($a); // class Foo#1 (0)
var_dump($b); // class Foo#2 (0)

PHP allows you to create an object instance from a variable like this: PHP允许您从变量创建对象实例,如下所示:

$a = 'Foo';
$b = new $a;

So when you use the new $a , PHP is checking if it's a string to make a new instance of the class, and if it's an object, it's going to retrieve the class name of the object instance and make a new instance from it. 因此,当你使用new $a ,PHP正在检查它是否是一个字符串来创建类的新实例,如果它是一个对象,它将检索对象实例的类名并从中创建一个新实例。

If you try to do the same with a non-string or non-object variable: 如果您尝试对非字符串或非对象变量执行相同操作:

$a = 1;
$b = new $a;

This will generate an error: 这将产生一个错误:

PHP Error: Class name must be a valid object or a string PHP错误:类名必须是有效对象或字符串

PHP 5.3.0 introduced a couple of new ways to create instances of an object, which is an example of a scenario like you've provided: PHP 5.3.0引入了一些创建对象实例的新方法,这是您提供的方案的一个示例:

class Test {}

$obj1 = new Test();
$obj2 = new $obj1;

For more information: Read Example #5 Creating new objects under https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.new 有关更多信息,请参阅示例#5在 https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.new 下创建新对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM