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
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php