Req #63693 [Opn->Csd]: Create objects with array of parameters
| From: | requinix@php.net | Date: | Thu, 17 Jul 2014 19:15:08 +0000 |
| Subject: | Req #63693 [Opn->Csd]: Create objects with array of parameters | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-186705@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=63693&edit=1
ID: 63693
Updated by: requinix@php.net
Reported by: rayro at gmx dot de
Summary: Create objects with array of parameters
-Status: Open
+Status: Closed
Type: Feature/Change Request
Package: Class/Object related
Operating System: Any
PHP Version: Irrelevant
-Assigned To:
+Assigned To: requinix
Block user comment: N
Private report: N
New Comment:
Added in PHP 5.6 as argument unpacking.
https://wiki.php.net/rfc/argument_unpacking
// function __construct($one, $four, $eight)
new MyClass(...[1, 4, 8]);
Previous Comments:
------------------------------------------------------------------------
[2012-12-05 07:48:15] rayro at gmx dot de
Description:
------------
Currently it is (not possible) to create an object using an array of parameters.
You have to type in each parameter for the constructor manually... (see script #1)
As it is possible to call functions using call_user_func_array, it would also be nice to create
objects like that. The only trick to make this possible is to make the use of Reflection. (see
script #2)
The paranthesis indicate that the arguments for __construct will be passed. The idea is to omit the
paranthesis and pass the arguments as array. (see script #3)
But this is only my idea... Maybe the best way is to provide a function for that, like
call_user_func_array() for functions exists... (see script #4)
Additionally another idea is to change the way "new" works, enabling to pass parameters to
new. (see script #5)
But for me, #3 is the best solution, because IF it would be possible in future releases of php to
cast to an object, the new keyword can simply be omitted while making the use of paranthesis. (see
script #6)
thx for listenig :)
Test script:
---------------
#1
<?php
$obj = new MyClass(1,4,8);
?>
#2
<?php
$class = new ReflectionClass('MyClass'));
$obj = $class->newInstanceArgs($array);
?>
#3
<?php
$obj = new MyClass $array;
?>
#4
<?php
$obj = create_instance('MyClass', $array);
?>
#5
<?php
$obj = new(MyClass, $array); # possible solution 1
$obj = new('MyClass', $array); # possible solution 2
?>
#6
<?php
$object = (MyClass) $array;
?>
Expected result:
----------------
A function or language construct to provide making objects of classes quickly.
Actual result:
--------------
No way instead of making the use of Reflection...
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=63693&edit=1