CKTIS / PHP
Keyword as
In foreach, as binds each item to a value variable and optionally a key variable.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
foreach ($rows as $key => $value)In foreach, as binds each item to a value variable and optionally a key variable. The default value binding is by value. A reference binding can update the original elements and remains bound after the loop until unset. In imports as introduces an alias. In trait adaptations it can add a method alias or simply change visibility, as in m as private without any new name.
$rows = ["left"=>2,"right"=>5];
foreach ($rows as $key => &$value) { $value += strlen($key); }
unset($value); echo json_encode($rows);
trait T { public function m(): string{return "kept";} } class Box { use T { m as private; } public function read(): string {return $this->m();} }
$x=new Box(); echo PHP_EOL,json_encode([$x->read(),is_callable([$x,"m"])]);
{"left":6,"right":10}
["kept",false]
Examples
<?php
$rows = ["left"=>2,"right"=>5];
foreach ($rows as $key => &$value) { $value += strlen($key); }
unset($value); echo json_encode($rows);
trait T { public function m(): string{return "kept";} } class Box { use T { m as private; } public function read(): string {return $this->m();} }
$x=new Box(); echo PHP_EOL,json_encode([$x->read(),is_callable([$x,"m"])]);
Result
{"left":6,"right":10}
["kept",false]