Newsgroups: php.internals Path: news.php.net Xref: news.php.net php.internals:109414 Return-Path: Delivered-To: mailing list internals@lists.php.net Received: (qmail 76240 invoked from network); 29 Mar 2020 17:05:31 -0000 Received: from unknown (HELO localhost.localdomain) (76.75.200.58) by pb1.pair.com with SMTP; 29 Mar 2020 17:05:31 -0000 To: internals@lists.php.net References: Date: Sun, 29 Mar 2020 17:31:14 +0200 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:52.0) Gecko/20100101 Firefox/52.0 SeaMonkey/2.49.2 MIME-Version: 1.0 In-Reply-To: Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Posted-By: 46.59.72.204 Subject: Re: [PHP-DEV] [RFC] [DISCUSSION] Compact Object Property Assignment From: ajf@ajf.me (Andrea Faulds) Message-ID: Hi Rowan, Rowan Tommins wrote: > > Hi Jakob, > > It occurred to me thinking about alternative syntaxes that COPA could be > seen as a limited form of the "with" statement found in some languages, > e.g. JS [1], VisualBasic [2], Delphi [3], Groovy [4] (note that with > blocks in Python are something different). This is a good point, though thinking about it made me realise you can already implement something like the proposed syntax in userland PHP: (function ($obj) { $foo = "foo"; $bar = "bar"; $baz = "baz"; $vars = get_defined_vars(); foreach ($vars as $key => $value) { $obj->$key = $value; } })($object); It's not very elegant though, and unfortunately you can't move the get_defined_vars() part to another function. You could do: use function \get_defined_vars as gdv; function assign(object $object, callable $assigner) { foreach ($assigner() as $key => $value) { $object->$key = $value; } } $object = new stdClass; assign($object, function () { $foo = "foo"; $bar = "bar"; $baz = "baz"; return gdv(); }); (By the way, if you want to reference existing properties, you can add an extra foreach loop to import them into the current scope, or use extract().) But then I realise that you don't even need the closure, you can just use a normal array, and it feels less necessary to add this to PHP core. If using an assign() function is inconvenient, it could be part of an object's constructor. Hmm… Thanks, Andrea