php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #63693 Create objects with array of parameters
Submitted: 2012-12-05 07:48 UTC Modified: 2014-07-17 19:15 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: rayro at gmx dot de Assigned: requinix (profile)
Status: Closed Package: Class/Object related
PHP Version: Irrelevant OS: Any
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: rayro at gmx dot de
New email:
PHP Version: OS:

 

 [2012-12-05 07:48 UTC] 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...

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-07-17 19:15 UTC] requinix@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: requinix
 [2014-07-17 19:15 UTC] requinix@php.net
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]);
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Oct 31 23:01:28 2024 UTC