Home > Software design >  php constructor is not working properly in program
php constructor is not working properly in program

Time:11-21

Please refer this Code input

This code doesn't give the expected output

class User{
        protected $name;
        protected $age;

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

    class Customer extends User{
        private $balance;

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

        public function pay($amount){
            return $this->name . ' paid $' . $amount;
        }
    }

    $customer1 = new Customer('Adithya', 23, 50);
    echo $customer1->pay(100);

It only gives this
Can someone please explain the reason?

CodePudding user response:

Add the following line to the Customer class constructor so that the parent class constructor is called with the right parameters

parent::__construct($name, $age);

So the code is as follows

(I have added a line in the pay method to make it more meaningful)

<?php
class User{
        protected $name;
        protected $age;

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

    class Customer extends User{
        private $balance;

        public function __construct($name, $age, $balance){
            parent::__construct($name, $age);
            $this->balance = $balance;
        }

        public function pay($amount){
            $this->balance = $this->balance - $amount;
            return $this->name . ' paid ' . $amount;
        }

        public function getbalance(){
            return $this->name . ' now has ' . $this->balance ;
        }

    }

    $customer1 = new Customer('Adithya', 23, 50);
    echo $customer1->pay(100);

    echo "<br>";

    echo $customer1->getbalance();
    ?>

The display will be :

Adithya paid 100
Adithya now has -50

(initially Adithya is having 50 as balance, but he has paid 100, so the new balance is -50)

CodePudding user response:

    class Customer extends User{
    private $balance;

    public function __construct($name, $age, $balance){
        $this->balance = $balance;
        parent::__construct($name,$age,$balance);
    }

    public function pay($amount){
        return $this->name . ' paid $' . $amount;
    }
}
  • Related