从类继承时忽略某些方法

我正在学习 oop 并使用 PHP 练习这些概念。我想做的是有一个 classHuman和一个 class Dog。类Human将有两个属性:$name:string和$age:int。类Human首先被声明,有一个方法speak()。我的问题是,当Dog扩展自时Humans,我希望它拥有Human除了方法之外的所有内容speak(),它将被其独特的方法所取代bark()。根据我的搜索,一个解决方案是设置speak()为private,然后Dog不会继承它。但是,当分配Human给 时$person,speak()由于它是私有的,因此也无法访问。这只是我理解oop的一种做法。如果这是一个真正的软件,在最佳实践方面我应该怎么做?同样,我是 oop 的初学者。谢谢!


这是我的代码:


<?php


    class Human {

      public $name;

      public $age;


      public function __construct($name, $age) {

        $this->name = $name;

        $this->age = $age;

      }


      public function speak() {


      }

    }


    class Dog extends Human {

      public function bark() {


      }

    }


    $people = array();

    $dogs = array();


    array_push($dogs, new Dog("Rocky", 4));

    array_push($people, new Human("Carlos", 21));


    $people[0]->speak();

    $dogs[0]->bark();


?>


一只萌萌小番薯
浏览 122回答 1
1回答

慕莱坞森

就 OOP 而言,Dog 扩展 Human 没有任何意义。想一想,只是没有任何意义。你可以做的实际上是定义一个抽象类或一个 Dog 和 Human 都从中扩展的接口。像这样:abstract class Animal&nbsp;{&nbsp; &nbsp; &nbsp;abstract public function communicate();&nbsp; &nbsp; &nbsp;...anyOtherMethods that are commom between dogs and Humans}class Human extends Animal&nbsp;{&nbsp; &nbsp; &nbsp;public function communicate()&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; echo 'speak';&nbsp; &nbsp; &nbsp;}}class Dog extends Animal{&nbsp; &nbsp; &nbsp;public function communicate()&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; echo 'bark';&nbsp; &nbsp; &nbsp;}}(new Dog)->communicate(); // bark(new Human)->communicate(); //speak
打开App,查看更多内容
随时随地看视频慕课网APP