QUIZGUM

Coding Class

Quizgum : Passing data to the constructor

Passing data to the constructor

You learned about constructors earlier.
Let's see how to pass data to the constructor.
It's no different from using a parameter when declaring a function and using arguments when calling a function. ^^

How to pass data to the constructor

  1. variable = new class name(argument, argument2, argument3)

How to receive data from the constructor

  1. function __construct(parameter, parameter2, parameter3){}

So let's do it. Let's use the Car class we used earlier.

  1. <?php
  2. class Car
  3. {
  4. public $wheels;
  5. public $doors = 4;
  6. protected $color = 4;
  7. private $size;
  8. private $company;
  9.  
  10. function __construct($company)
  11. {
  12. echo "I started to run my car {$company}.";
  13. }
  14.  
  15. public function run()
  16. {
  17. return "The car is running.";
  18. }
  19.  
  20. protected function stop()
  21. {
  22. return "car stops.";
  23. }
  24.  
  25. protected function turn()
  26. {
  27. return "turnning car";
  28. }
  29. }
  30. $mercedes = new Car('made by benz');
  31. ?>

Result of the code above

passing two, three, or four data to the constructor is no different from that of a function.

  1. <?php
  2. class Car
  3. {
  4. public $wheels;
  5. public $doors = 4;
  6. protected $color = 4;
  7. private $size;
  8. private $company;
  9.  
  10. function __construct($company, $color, $machine)
  11. {
  12. echo "Start up to operate a {$color} {$machine} made by {$company}";
  13. }
  14.  
  15. public function run()
  16. {
  17. return "The car is running.";
  18. }
  19.  
  20. protected function stop()
  21. {
  22. return "car stops.";
  23. }
  24.  
  25. protected function turn()
  26. {
  27. return "turnning car";
  28. }
  29. }
  30. $mercedes = new Car('benz', 'red', 'motorbike');
  31. ?>

Result