Re: Set object properties inline
| From: | Fleshgrinder | Date: | Wed, 01 Jun 2016 17:38:37 +0000 |
| Subject: | Re: Set object properties inline | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-93683@lists.php.net to get a copy of this message | ||
On 6/1/2016 5:47 PM, Ryan Pallas wrote:
> On Wed, Jun 1, 2016 at 9:37 AM, Matt Fonda <matthewfonda@gmail.com> wrote:
>>
>>
>> Hi Jesse,
>>
>> It's fairly straightforward to implement a function that does this in
>> userland, for example something like the following:
>>
>> function f($fqcn, $args) {
>> $instance = new $fqcn;
>> foreach ($args as $key => $value) {
>> $instance->$key = $value;
>> }
>> return $instance;
>> }
>> ...
>> $this->fooMethod(
>> $arg1,
>> $arg2,
>> f('FooParams', [
>> 'prop1' => ...,
>> 'prop2' => ...,
>> 'prop3' => f('Obj1', [
>> 'prop1' => ...,
>> 'prop2' => ...,
>> ],
>> ])
>> );
>>
>> You may also use the approach Peter suggested. As such, I don't think
>> introducing a new syntax for it is necessary.
>>
>
> I disagree here. This lets you add dynamic properties accidentally (by
> putting too many entries in the array or misspelling a property as a key),
> this method does not let IDEs help you with the construction of the array,
> or even what's valid for each value in that array and doesn't provide any
> language level protection against misspelled properties. Of course, for the
> last point, I'm assuming that this idea works like the following:
>
> class Foo {
> public $prop1;
> }
>
> new Foo () {
> porp1 = 'foo' // undefined property error of some sort
> };
>
>
>> Best,
>> --Matt
>>
>
Still generically solvable in userland with creativity. :)
trait ObjectFromArray {
public static function fromArray(array $array, ...$params) {
$object = new static(...$params);
foreach ($array as $k => $v) {
if (property_exists($object, $k)) {
$object->{$k} = $v;
}
else {
trigger_error('fubar', E_USER_ERROR);
}
}
return $object;
}
}
class SomeObject {
use ObjectFromArray;
private $foo;
}
SomeObject::fromArray(['foo' => 'bar', 'bar' =>
'foo']);
--
Richard "Fleshgrinder" Fussenegger
Attachment: [application/pgp-signature] OpenPGP digital signature signature.asc
Attachment: [application/pgp-signature] OpenPGP digital signature signature.asc