一個接口定義了類必須遵守的合同。 它指定方法簽名而不提供實現。 然後,類
實現接口,為方法提供了自己的具體實現。
// Define an interface interface Shape { public function getArea(); } // Implement the interface in different classes class Circle implements Shape { private $radius; public function __construct($radius) { $this->radius = $radius; } public function getArea() { return pi() * $this->radius * $this->radius; } } class Square implements Shape { private $side; public function __construct($side) { $this->side = $side; } public function getArea() { return $this->side * $this->side; } } // Using polymorphism $shapes = [new Circle(5), new Square(4)]; foreach ($shapes as $shape) { echo "Area: " . $shape->getArea() . PHP_EOL; }
>和Circle
被視為Square
>對象。 Shape
循環通過包含兩種類型的數組迭代,每個類型都在每種類型上調用foreach
getArea()
<> 摘要類與接口相似,但可以為某些方法提供默認實現。 它們不能直接實例化;子類必須擴展它們並為任何抽象方法提供實現。
<>
// Define an abstract class abstract class Animal { public function speak() { echo "Generic animal sound" . PHP_EOL; } abstract public function move(); } // Extend the abstract class class Dog extends Animal { public function move() { echo "Dog is running" . PHP_EOL; } } class Bird extends Animal { public function move() { echo "Bird is flying" . PHP_EOL; } } // Using polymorphism $animals = [new Dog(), new Bird()]; foreach ($animals as $animal) { $animal->speak(); $animal->move(); }
> Dog
從Bird
繼承,並提供其對Animal
方法的具體實現。 該方法在抽像類中具有默認實現,但是如果需要的話,子類可以覆蓋它。 move()
>speak()
>在PHP 7應用中使用多態性的應用有什麼實際好處?
saceario 1:database互動:
>Database
connect()
query()
disconnect()
MySQLDatabase
PostgreSQLDatabase
Database
,和
。 您的應用程序代碼可以使用PaymentGateway
>接口與數據庫進行交互,而不管實際使用的數據庫系統如何。 切換數據庫僅需要更改混凝土類的實例。 processPayment()
StripePaymentGateway
PayPalPaymentGateway
PaymentGateway
方案2:付款處理:
>您可能有不同的付款網關(Stripe,PayPal)。使用
之類的方法創建一個接口。 例如Logger
和log()
之類的實現將處理每個網關的細節。 您的購物車應用程序可以使用FileLogger
>接口,使您可以輕鬆地添加新的付款選項而不更改核心功能。 混凝土類,例如DatabaseLogger
>,EmailLogger
,Logger
將處理特定的日誌記錄方法。您的應用程序可以使用
>
>這些示例表明了多態性如何通過將應用程序邏輯從特定實現中解除應用程序來促進靈活性,可維護性和可擴展性。 這會導致更清潔,更健壯且易於維護的PHP 7應用程序。以上是如何在PHP 7中使用多態性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!