解析错误:语法错误,第 20 行的 .../test6_2.php 中出现意外的“新”(T_NEW)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38675762/
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 01:40:20  来源:igfitidea点击:

Parse error: syntax error, unexpected 'new' (T_NEW) in .../test6_2.php on line 20

phpreferenceoperators

提问by 1000Gbps

Just trying to save and fix sources from PHPBench.com

只是试图从PHPBench.com保存和修复源代码

and hit this error (the site is down and the author didn't respond to questions). This is the source:

并遇到此错误(该站点已关闭并且作者没有回答问题)。这是来源:

<?php

// Initial Configuration
class SomeClass {
  function f() {

  }
}
$i = 0; //fix for Notice: Undefined variable i error

// Test Source
function Test6_2() {
  //global $aHash; //we don't need that in this test
  global $i; //fix for Notice: Undefined variable i error

  /* The Test */
  $t = microtime(true);
  while($i < 1000) {
    $obj =& new SomeClass();
    ++$i;
  }

  usleep(100); //sleep or you'll return 0 microseconds at every run!!!
  return (microtime(true) - $t);
}

?>

Is it a valid syntax or not? Correct me if I'm wrong but think it creates a reference to SomeClass, so we can call new $obj()... Thanks in advance for the help

它是否是有效的语法?如果我错了,请纠正我,但认为它创建了对 SomeClass 的引用,因此我们可以调用new $obj()... 在此先感谢您的帮助

采纳答案by Bill Karwin

Objects are always stored by reference anyway. You don't need =&and as Charlotte commented, it's deprecated syntax.

无论如何,对象总是通过引用存储。您不需要=&,正如 Charlotte 评论的那样,它是不推荐使用的语法。

Correct me if I'm wrong but think it creates a reference to SomeClass, so we can call new $obj() .

如果我错了,请纠正我,但认为它创建了对 SomeClass 的引用,因此我们可以调用 new $obj() 。

No, this is not correct. The newoperator always creates an instance of the class, not a reference to the class as a type.

不,这是不正确的。的new操作者总是创建的类,而不是对类的引用作为一种类型的实例。

You can create a variable object instantiation simply by creating a stringvariable with the name of the class, and using that.

您可以简单地通过创建一个带有类名的字符串变量并使用它来创建一个变量对象实例化。

$class = "MyClass";
$obj = new $class();

Functions like get_class()or ReflectionClass::getName()return the class name as a string. There is no "reference to the class" concept in PHP like there is in Java.

get_class()ReflectionClass::getName()等函数将类名作为字符串返回。PHP 中没有像 Java 中那样的“对类的引用”概念。

The closest thing you're thinking of is ReflectionClass::newInstance()but this is an unnecessary way of creating an object dynamically. In almost every case, it's better to just use new $class().

您想到的最接近的是ReflectionClass::newInstance() ,但这是动态创建对象的不必要方法。在几乎所有情况下,最好只使用new $class().