Using as
in a foreach
loop:
<?php
$list = [1, 2, 3, 4];
foreach($list as $item) {
echo $item;
echo "<br>";
}
?>
Try it Yourself »
The as
keyword is used by the foreach
loop to establish which variables contain the key and value of an element.
The as
keyword can also be used by namespaces and traits to give them an alias.
The foreach
keyword.
The trait
keyword.
The use
keyword.
Read more about loops in our PHP Loops Tutorial.
Read more about traits in our PHP OOP - Traits Tutorial.
Using as
in a foreach
loop to traverse an associative array:
<?php
$people = [
"Peter" => "35",
"Ben" => "37",
"Joe" => "43"
];
foreach($people as $person => $age) {
echo "$person is $age years old";
echo "<br>";
}
?>
Try it Yourself »
Using as
to give an alias to the method of a trait
:
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
class Welcome {
use message1 {
message1::msg1 as msg;
}
}
$obj = new Welcome();
$obj->msg();
?>
Try it Yourself »
Using as
to give an alias to a namespace
:
<?php
namespace Html;
class Table {
public $title = "";
public $numRows = 0;
public function message() {
echo "<p>Table '{$this->title}' has {$this->numRows} rows.</p>";
}
}
use \Html as H;
$table = new H\Table();
$table->title = "My table";
$table->numRows = 5;
$table->message();
?>
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!