Parse error: syntax error, unexpected 'new' (T_NEW) in .../test6_2.php on line 20
Objects are always stored by reference anyway. You don't need =&
and as Charlotte commented, it's deprecated syntax.
Correct me if I'm wrong but think it creates a reference to SomeClass, so we can call new $obj() .
No, this is not correct. The new
operator always creates an instance of the class, not a reference to the class as a type.
You can create a variable object instantiation simply by creating a string variable 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.
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()
.
1000Gbps
Tryin' to frustrate more people with less AI than usual Tryin' to solder some wires without blowing up the PCB Tryin' to survive the chaos in the modern world ... but still only trying'
Updated on July 09, 2022Comments
-
1000Gbps almost 2 years
Just trying to save and fix sources from 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