php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #51808 Operator `new' does not support expressions for class name
Submitted: 2010-05-13 12:53 UTC Modified: 2021-05-31 14:51 UTC
Votes:1
Avg. Score:3.0 ± 0.0
Reproduced:0 of 0 (0.0%)
From: m dot przybylski at bkfmyjnie dot pl Assigned: cmb (profile)
Status: Closed Package: Class/Object related
PHP Version: 5.2.13 OS: linux/current
Private report: No CVE-ID: None
 [2010-05-13 12:53 UTC] m dot przybylski at bkfmyjnie dot pl
Description:
------------
Operator `new' accepts either class name as either symbol token or variable
containing class name (T_STRING or
T_VARIABLE), but does not allow expressions returning class name.

Test script:
---------------
/* first form, works */
$handler = new SomeClass($constructorParam);

/* second form, works */
$handlerClass = handlerFor($something); /* returns name of some class to be instantiated */
$handler = new $handlerClass($constructorParam);

/* third form -- does not work */
$handler = new (handlerFor($something))($constructorParam);

Expected result:
----------------
The third form ought to work just like the other two, so one doesn't need to
create extra variable for single use.

Actual result:
--------------
PHP Parse error:  syntax error, unexpected '(', expecting T_STRING or T_VARIABLE
or '$'

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-08-03 17:58 UTC] + at ni-po dot com
Imho this isn't obvious at all. At least your proposed syntax `new (func())()` isn't quite readable or understandable.
 [2010-08-03 22:47 UTC] giorgio dot liscio at email dot it
does not works too:

new MyClass()->method();
(new MyClass())->method();

new ($className = FuncGetClassAsString())();

these are not really important to fix, but are welcome, in future maybe
 [2021-05-31 14:51 UTC] cmb@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: cmb
 [2021-05-31 14:51 UTC] cmb@php.net
This is supported as of PHP 8.0.0[1].

[1] <https://3v4l.org/2bbfa>
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Mar 19 02:01:28 2024 UTC