PHP面向对象编程基础(二)

继承

继承是一种面向对象编程的概念,它允许我们创建一个新的类,该类从现有的类中继承属性和方法。继承可以减少代码重复,并允许我们构建更复杂的对象层次结构。

class Animal {
  protected $name;

  public function __construct($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

class Dog extends Animal {
  public function bark() {
    echo "Woof!";
  }
}

$dog = new Dog("Fido");
echo $dog->getName(); // 输出 "Fido"
$dog->bark(); // 输出 "Woof!"

在上面的例子中,我们定义了一个名为Animal的类,它有一个名为name的属性和一个名为getName()的方法。我们还定义了一个名为Dog的类,它从Animal类继承了name属性和getName()方法,并添加了一个名为bark()的方法。

多态性

多态性是面向对象编程的一个概念,它允许我们使用相同的方法来处理不同类型的对象。多态性可以提高代码的灵活性和可扩展性。

class Shape {
  protected $color;

  public function __construct($color) {
    $this->color = $color;
  }

  public function getColor() {
    return $this->color;
  }

  public function getArea() {
    // 抽象方法
  }
}

class Rectangle extends Shape {
  protected $width;
  protected $height;

  public function __construct($color, $width, $height) {
    parent::__construct($color);
    $this->width = $width;
    $this->height = $height;
  }

  public function getArea() {
    return $this->width * $this->height;
  }
}

class Circle extends Shape {
  protected $radius;

  public function __construct($color, $radius) {
    parent::__construct($color);
    $this->radius = $radius;
  }

  public function getArea() {
    return pi() * pow($this->radius, 2);
  }
}

$shapes = array(
  new Rectangle("red", 5, 10),
  new Circle("blue", 3)
);

foreach
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaoyi9812

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值