一个接口定义了类必须遵守的合同。 它指定方法签名而不提供实现。 然后,类
实现接口,为方法提供了自己的具体实现。
<code class="php">// 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; }</code>在此示例中,
>和Circle
被视为Square
>对象。 Shape
循环通过包含两种类型的数组迭代,每个类型都在每种类型上调用foreach
getArea()
摘要类与接口相似,但可以为某些方法提供默认实现。 它们不能直接实例化;子类必须扩展它们并为任何抽象方法提供实现。
<code class="php">// 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(); }</code>和
> 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中文网其他相关文章!