在 PHP7 中,如果您需要定義 Array 類型的常量,那么通過使用 define()函數(shù)進(jìn)行定義是一個(gè)不錯(cuò)的選擇。使用過 PHP 5.6 版本的朋友應(yīng)該知道,在 PHP5.6 中,只能使用 const 關(guān)鍵字來定義數(shù)組類型的常量。
<?php
//define a array using define function
define('fruit', [
'apple',
'orange',
'banana'
]);
print(fruit[1]);
?>
它產(chǎn)生以下瀏覽器輸出 :
orange
現(xiàn)在,您可以在 PHP7 中使用 new class 來定義(實(shí)例化)匿名類。匿名類可以用來代替完整的類定義。
<?php
interface Logger {
public function log(string $msg);
}
class Application {
private $logger;
public function getLogger(): Logger {
return $this->logger;
}
public function setLogger(Logger $logger) {
$this->logger = $logger;
}
}
$app = new Application;
$app->setLogger(new class implements Logger {
public function log(string $msg) {
print($msg);
}
});
$app->getLogger()->log("My first Log Message");
?>
它產(chǎn)生以下瀏覽器輸出:
My first Log Message
可以將參數(shù)傳遞到匿名類的構(gòu)造器,也可以擴(kuò)展(extend)其他類、實(shí)現(xiàn)接口(implement interface),以及像其他普通的類一樣使用 trait:
<?php
class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}
var_dump(new class(10) extends SomeClass implements SomeInterface {
private $num;
public function __construct($num)
{
$this->num = $num;
}
use SomeTrait;
});
?>
它產(chǎn)生以下瀏覽器輸出:
object(class@anonymous)#1 (1) {
["Command line code0x104c5b612":"class@anonymous":private]=>
int(10)
}
匿名類被嵌套進(jìn)普通 Class 后,不能訪問這個(gè)外部類(Outer class)的 private(私有)、protected(受保護(hù))方法或者屬性。 為了訪問外部類(Outer class)protected 屬性或方法,匿名類可以 extend(擴(kuò)展)此外部類。 為了使用外部類(Outer class)的 private 屬性,必須通過構(gòu)造器傳進(jìn)來:
<?php
class Outer
{
private $prop = 1;
protected $prop2 = 2;
protected function func1()
{
return 3;
}
public function func2()
{
return new class($this->prop) extends Outer {
private $prop3;
public function __construct($prop)
{
$this->prop3 = $prop;
}
public function func3()
{
return $this->prop2 + $this->prop3 + $this->func1();
}
};
}
}
echo (new Outer)->func2()->func3();
?>
它產(chǎn)生以下瀏覽器輸出:
6
更多建議: