【问题标题】:can i make this work without using __constructor我可以在不使用构造函数的情况下完成这项工作吗
【发布时间】:2021-12-23 19:27:56
【问题描述】:

我正在研究与此问题稍有相似的其他问题。我试图做的是创建一个具有私有属性的类(或者不知道到底是什么)并私有存储在一个类中,然后像这样进行继承:

(我想进一步澄清我的解释,但我在编程中的词汇量非常有限)

 <?php
        class Fruit {
          private $name;
          private $color;
          public function patients($name, $color) {
            $this->name = $name;
            $this->color = $color;
          }
         
          public function intro() {
            echo "The fruit is {$this->name} and the color is {$this->color}.";
          }
        }
        
        // Strawberry is inherited from Fruit
        class Strawberry extends Fruit {
          public function message() {
            echo $this->intro();
          }
          
        }
    
    $strawberry = new Strawberry("Strawberry", "red");
    $strawberry->message();
    
    ?>

【问题讨论】:

    标签: php oop inheritance


    【解决方案1】:

    是的,你可以。你应该使用你声明的方法而不是使用构造函数(new Strawberry("Strawberry", "red");)如果你没有设置它并且不想使用它):

    <?php
    class Fruit {
      private $name;
      private $color;
      public function describe($name, $color) {
        $this->name = $name;
        $this->color = $color;
      }
    
      public function intro() {
        echo "The fruit is {$this->name} and the color is {$this->color}.";
      }
    }
    
    // Strawberry is inherited from Fruit
    class Strawberry extends Fruit {
      public function message() {
        echo $this->intro();
      }
    }
    

    将您的方法 patients() 重命名为 describe() 更合适。删除了您的方法assignPatient(),因为您没有使用它,它基本上与describe() 所做的相同。 您现在可以使用

    $strawberry = new Strawberry();
    $strawberry->describe("Strawberry", "red");
    $strawberry->message();
    

    输出“水果是草莓,颜色是红色的。”。

    您实际上也可以删除您的 message() 方法并改为调用 intro()

    $strawberry = new Strawberry();
    $strawberry->describe("Strawberry", "red");
    $strawberry->intro();
    

    【讨论】:

    • 非常感谢我向你学习
    猜你喜欢
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 2011-04-20
    • 2016-11-04
    • 1970-01-01
    • 2014-07-12
    相关资源
    最近更新 更多