面向对象编程中,多态性允许对象以不同的方式响应相同方法调用,而继承性允许子类继承和扩展父类功能。多态性表现为不同类型对象对同一方法的差异化响应,如动物类、狗类和猫类对象的 speak() 方法。继承性则体现在子类从父类继承数据和方法,如员工类从人类类继承姓名和年龄,并新增工资属性。在实际案例中,猕猴桃类继承水果类的水果名称,而跑车类通过多态性重写父类中的 gettype() 方法,实现了对汽车类中相同方法的不同响应,分别返回“汽车”和“跑车”的类型信息。
PHP 对象导向编程进阶:理解多态和继承
概述
多态和继承是面向对象编程 (OOP) 的两个基本概念。多态允许对象以不同的方式响应相同的方法调用,而继承允许创建新类,它们继承并扩展现有类的功能。
多态
多态允许对象根据其类型执行不同的操作。
class Animal { public function speak() { echo "Animal speaksn"; } } class Dog extends Animal { public function speak() { echo "Dog barksn"; } } class Cat extends Animal { public function speak() { echo "Cat meowsn"; } } $dog = new Dog(); $dog->speak(); // 输出:Dog barks $cat = new Cat(); $cat->speak(); // 输出:Cat meows
登录后复制
继承
继承允许创建新类(子类),这些类从现有类(父类)继承数据和方法。
class Person { protected $name; protected $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } public function getName() { return $this->name; } } class Employee extends Person { private $salary; public function __construct($name, $age, $salary) { parent::__construct($name, $age); // 调用父类构造函数 $this->salary = $salary; } public function getSalary() { return $this->salary; } } $employee = new Employee("John Doe", 30, 50000); echo "Employee name: " . $employee->getName() . "n"; echo "Employee salary: " . $employee->getSalary() . "n";
登录后复制
实战案例
水果类和猕猴桃类(继承)
class Fruit { protected $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } } class Kiwi extends Fruit { public function __construct() { parent::__construct("Kiwi"); } } $kiwi = new Kiwi(); echo "Fruit name: " . $kiwi->getName() . "n";
登录后复制
汽车类和跑车类(多态)
class Car { protected $make; protected $model; public function __construct($make, $model) { $this->make = $make; $this->model = $model; } public function getType() { return "Car"; } } class SportsCar extends Car { public function getType() { return "Sports Car"; } } $car = new Car("Toyota", "Camry"); $sportsCar = new SportsCar("Ferrari", "F430"); echo "Car type: " . $car->getType() . "n"; echo "Sports car type: " . $sportsCar->getType() . "n";
登录后复制
以上就是PHP 对象导向编程进阶:理解多态和继承的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:weapp,转转请注明出处:https://www.dingdanghao.com/article/453695.html