CKTIS / PHP
Parola chiave as
In foreach lega l’elemento a una variabile di valore e facoltativamente alla chiave.
Versione: PHP 8.4; repository runtime, production runtime not attested
Sintassi
foreach ($rows as $key => $value)In foreach lega l’elemento a una variabile di valore e facoltativamente alla chiave. Per default il valore è copiato, un riferimento modifica l’elemento. Dopo il ciclo rimuovilo con unset. Negli import as introduce un alias. In un trait può aggiungere un alias di metodo o cambiare solo la visibilità, come m as private senza rinominare.
$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]
Esempi
<?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"])]);
Risultato
{"left":6,"right":10}
["kept",false]