Home > Software design >  can i make this work without using __constructor
can i make this work without using __constructor

Time:11-11

i was working on something else slightly similar to this problem. what im trying to do is to make a class with private properties (or something don't know what exactly call this) and privately stored in a class and then make an inheritance like this:

(i want to clarify my explanation further more but my vocabular in programming is very limited)

 <?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();
    
    ?>

CodePudding user response:

Yes you can. You should use the methods you declared and not use the constructor (new Strawberry("Strawberry", "red");) if you haven't set it up and don't want to use it):

<?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();
  }
}

Renamed your method patients() to describe() to be more fitting. Removed your method assignPatient() since you didn't use it and it basically did the same what describe() does. You can now use

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

to output "The fruit is Strawberry and the color is red.".

You could in fact also remove your message() method and call intro() instead:

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