結論:
- PHP中提供了反射類來決議類的結構;
- 通過反射類可以獲取到類的建構式及其引數和依賴;
- 給建構式的引數遞回設定默認值后,即可使用這些帶默認值的引數通過
newInstanceArgs實體化出類物件; - 在實體化的程序中,依賴的類也會被實體化,從而實作了依賴注入,
PHP中反射類的常用方法:
// 通過類名 Circle 實體化反射類
$reflectionClass = new reflectionClass(Circle::class);
// 獲取類常量
$reflectionClass->getConstants();
// 獲取類屬性
$reflectionClass->getProperties();
// 獲取類方法
$reflectionClass->getMethods();
// 獲取類的建構式
$constructor = $reflectionClass->getConstructor();
// 獲取方法的引數
$parameters = $constructor->getParameters();
// 通過引數默認值陣列實體化類創建物件
$class = $reflectionClass->newInstanceArgs($dependencies);
創建兩個具有依賴關系的類:
class Point
{
public $x;
public $y;
public function __construct($x = 0, $y = 0)
{
$this->x = $x;
$this->y = $y;
}
}
class Circle
{
// 圓的半徑
public $radius;
// 圓心位置
public $center;
const PI = 3.14;
public function __construct(Point $point, $radius = 1)
{
$this->center = $point;
$this->radius = $radius;
}
// 列印圓心位置的坐標
public function printCenter()
{
printf('圓心的位置是:(%d, %d)', $this->center->x, $this->center->y);
}
//計算圓形的面積
public function area()
{
return 3.14 * pow($this->radius, 2);
}
}
創建兩個方法:
make 方法負責決議類和構建類的物件;
getDependencies 負責依賴決議并初始化引數默認值;
//構建類的物件
function make($className)
{
try {
$reflectionClass = new ReflectionClass($className);
$constructor = $reflectionClass->getConstructor();
$parameters = $constructor->getParameters();
$dependencies = getDependencies($parameters);
// 用指定的引數創建一個新的類實體
return $reflectionClass->newInstanceArgs($dependencies);
} catch (ReflectionException $e) {
throw new Exception("{$className} not found.");
}
}
//依賴決議并初始化引數默認值
function getDependencies($parameters)
{
$dependencies = [];
// Circle 類的引數為 point 和 radius
// Point 類的引數為 x 和 y
foreach($parameters as $parameter) {
$dependency = $parameter->getClass();
// 如果引數不是類
if (is_null($dependency)) {
// 可選引數,有默認值
if($parameter->isDefaultValueAvailable()) {
$dependencies[] = $parameter->getDefaultValue();
}
// 必傳引數暫時先給一個默認值
else {
$dependencies[] = '0';
}
}
// 如果引數是類
else {
// 遞回進行依賴決議
$dependencies[] = make($parameter->getClass()->name);
}
}
return $dependencies;
}
測驗:
// 實體化物件
$circle = make('Circle');
// 呼叫物件的方法
$area = $circle->area();
var_dump($circle, $area);
程序說明:
make('Circle')
getDependencies(Point, int)
make('Point')
getDependencies(int, int)
new Point(int, int);
return Point;
new Circle(Point, int);
return Circle;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/20915.html
標籤:PHP
上一篇:xxljob調度失敗
