解析错误:语法错误,意外'新' (T_NEW)在第20行的... / test6_2.php中

时间:2016-07-30 15:51:37

标签: php reference operators

只是尝试保存并修复PHPBench.com

中的来源

并点击此错误(网站已关闭且作者未对问题做出回应)。这是来源:

<?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);
}

?>

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

1 个答案:

答案 0 :(得分:10)

无论如何,对象总是通过引用存储。您不需要=&,正如Charlotte评论的那样,它已被弃用。

  

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

不,这不正确。 new运算符始终创建类的实例,而不是作为类型对类的引用。

您只需创建一个带有类名称的 string 变量并使用它来创建变量对象实例化。

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

get_class()ReflectionClass::getName()等函数将类名作为字符串返回。没有&#34;对班级的引用&#34; PHP中的概念就像在Java中一样。

您最关心的事情是ReflectionClass::newInstance(),但这是动态创建对象的不必要方式。几乎在所有情况下,最好只使用new $class()