PHP as 关键字
实例
在 foreach
循环中使用 as
:
<?php
$list = [1, 2, 3, 4];
foreach($list as $item) {
echo $item;
echo "<br>";
}
?>
亲自试一试 »
$list = [1, 2, 3, 4];
foreach($list as $item) {
echo $item;
echo "<br>";
}
?>
定义和用法
as
关键字被 foreach
循环用来确定哪些变量包含 元素。
as
关键字也可以被命名空间和特征使用来给它们一个别名。
相关页面
foreach
关键字。
trait
关键字。
使用
关键字。
在我们的 PHP 循环教程中了解更多关于循环的信息。
在我们的 PHP OOP - 特征教程 中阅读有关特征的更多信息。
更多实例
实例
在 foreach
循环中使用 as
来遍历关联数组:
<?php
$people = [
"Peter" => "35",
"Ben" => "37",
"Joe" => "43"
];
foreach($people as $person => $age) {
echo "$person is $age years old";
echo "<br>";
}
?>
亲自试一试 »
$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();
?>
亲自试一试 »
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();
?>
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();
?>