PHP as 關鍵字
示例
在 foreach
迴圈中使用 as
<?php
$list = [1, 2, 3, 4];
foreach($list as $item) {
echo $item;
echo "<br>";
}
?>
自己動手試一試 »
定義和用法
as
關鍵字由 foreach
迴圈使用,用於指定哪個變數包含元素的鍵和值。
as
關鍵字也可以由名稱空間和 traits 使用,為它們指定別名。
相關頁面
foreach
關鍵字。
trait
關鍵字。
use
關鍵字。
在我們的 PHP 迴圈教程 中閱讀有關迴圈的更多資訊。
在我們的 PHP OOP - Traits 教程 中閱讀有關 traits 的更多資訊。
更多示例
示例
在 foreach
迴圈中使用 as
遍歷關聯陣列
<?php
$people = [
"Peter" => "35",
"Ben" => "37",
"Joe" => "43"
];
foreach($people as $person => $age) {
echo "$person is $age years old";
echo "<br>";
}
?>
自己動手試一試 »
示例
使用 as
為 trait
的方法指定別名
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
class Welcome {
use message1 {
message1::msg1 as msg;
}
}
$obj = new Welcome();
$obj->msg();
?>
自己動手試一試 »
示例
使用 as
為 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();
?>
❮ PHP 關鍵字