CKTIS / PHP
Ključna riječ as
U foreach povezuje element s varijablom vrijednosti i po potrebi ključem.
Verzija: PHP 8.4; repository runtime, production runtime not attested
Sintaksa
foreach ($rows as $key => $value)U foreach povezuje element s varijablom vrijednosti i po potrebi ključem. Zadano se vrijednost kopira, a referenca mijenja element. Nakon petlje uklonite ju s unset. Pri uvozu as uvodi alias. U traitu može dodati alias metode ili promijeniti samo vidljivost, primjerice m as private bez preimenovanja.
$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]
Primjeri
<?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"])]);
Rezultat
{"left":6,"right":10}
["kept",false]