php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #65296 Support named parameters in constructors to inline initialize objects with new()
Submitted: 2013-07-19 10:20 UTC Modified: 2013-07-22 10:32 UTC
Votes:2
Avg. Score:2.0 ± 1.0
Reproduced:0 of 1 (0.0%)
From: llmll at gmx dot de Assigned:
Status: Wont fix Package: Scripting Engine problem
PHP Version: Irrelevant OS: any
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please — but make sure to vote on the bug!
Your email address:
MUST BE VALID
Solve the problem:
14 + 42 = ?
Subscribe to this entry?

 
 [2013-07-19 10:20 UTC] llmll at gmx dot de
Description:
------------
As PHP does not support *real* overloading by different parameter sets, arrays are being used for dynamic parameters as well as for object initialization in constructors.

However arrays use strings as keys, which kills syntax highlighting and refactoring capabilities in IDEs.

PHP engine should provide a way to initialize an object inline by dynamically providing parameters to new().


Test script:
---------------
$object = new Object({
    StringMember: "content",
    Counter: 42,
    ArrayMember: ["old" => "way"]
});

Expected result:
----------------
$object->StringMember = "content";
$object->Counter = 42;
$object->ArrayMember = array("old" => "way");
$object->MoreProperties = "stay untouched";

Actual result:
--------------
not possible.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-07-19 10:25 UTC] llmll at gmx dot de
-Summary: Support amed parameters in constructors to inline initialize objects with new() +Summary: Support named parameters in constructors to inline initialize objects with new()
 [2013-07-19 10:25 UTC] llmll at gmx dot de
typo in summary corrected
 [2013-07-19 17:42 UTC] mail+php at requinix dot net
Keeping in mind that your IDE could not possibly give you support for arbitrary 
properties on objects, they probably do support the @property phpdoc. Add that 
to __get/__set and you have

/**
 * @property string $StringMember
 * @property int $Counter
 * @property mixed[] $ArrayMember
 */
class Foo {
    private $data;
    public function __construct(array $data) { $this->data = $data; }
    public function __get($name) { return $this->data[$name]; }
    public function __set($name, $value) { $this->data[$name] = $value; }
}

$foo = new Foo([
    "StringMember" => "content",
    "Counter" => 42,
    "ArrayMember" => ["old" => "way"]
]);
$foo-> // should autocomplete/suggest StringMember, Counter, and ArrayMember

If you're talking about the {} syntax you used,
https://wiki.php.net/rfc/objectarrayliterals
 [2013-07-19 20:52 UTC] llmll at gmx dot de
I view as a strength of PHP, not having to declare all fields in a class. For example think of a class representing a HTML DOM element, like a link. It allow many fields, but most often you will only use some of them, like "href" or "class".

In my opinion the best syntax to write is something like:
$link = new Link(href: "target.html", class:"btn btn-info");

At the moment I use arrays:
$link = (new Link)->assign("href" => "target.html", "class" => "btn btn-info");

But the fields in the strings are messy and un-recognizeable.

Phpdoc is far too cluttering. Declaring every possible option is pointless for some classes, especially if they are highly dynamic, like derived from a database table.
 [2013-07-19 20:56 UTC] mail+php at requinix dot net
So object literals. Getting to use names instead of strings.

Meanwhile

$object = new Object();
$object->StringMember = "content";
// etc

doesn't work?
 [2013-07-19 21:05 UTC] llmll at gmx dot de
Of course its working, this is not about a bug but about sleekness and PHP-to-programmer support ;-)

These assignment-lists are really lengthy and contain too many repetitions.

Its more like requesting the ternary operator instead of the "old" if ... then ... else ...
 [2013-07-19 21:11 UTC] llmll at gmx dot de
Just forgot to mention one more readability advantage:

It would support "nested" initializations, like it is now possible with arrays full of strings

$object = new Object({
    Property: $aValue,
    Property2: $aValue2,
    Subobject: new Object({
      ...
    })
});
 [2013-07-22 10:27 UTC] ab@php.net
-Status: Open +Status: Wont fix
 [2013-07-22 10:27 UTC] ab@php.net
I really hope we won't turn php into javascript :) Please take a look, the sugar you 
talk about is possible with the following 

class Props {
        function __construct(array $argv) {
                foreach($argv as $arg => $val) {
                        $this->$arg = $val;
                }
        }
}

$u = new Props(['hello' => 'world',
                'good' => 'bye',
                'obj' => new Props(['my' => 'god'])]);

Or even use func_get_args() to make $argv optional.

However this is a VERY bad style. Every object property should be defined with the 
class.
 [2013-07-22 10:32 UTC] ab@php.net
What i mean, each property should be contained in the class declaration before 
it's actually defined in construct :)
 [2013-08-14 11:02 UTC] none at none dot de
I think the main point was missed: Original request was about Named Parameters. (http://en.wikipedia.org/wiki/Named_parameter)

This will not extend the language or its features but enhance code readability for both humans and IDEs.
 [2013-09-29 20:55 UTC] work at nowhere dot de
Hi, would really like to see this feature.

@ab, you did not understand the main request. Arrays *are* possible, but THESE are the bad style you talk about. Initializing properties by strings is error prone, since it is a concept brake: mapping anything-strings to defined-constants.

The OP talked about named constants in constructors. What is the problem with such a language feature?
 [2013-09-29 20:57 UTC] work at nowhere dot de
If anyone votes for "properties shoudl be defined in the class", why does php support magic setters and getters?
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Tue Apr 30 12:01:30 2024 UTC