QUIZGUM

Coding Class

Quizgum : construct

Using the constructor

The constructor is the first method automatically executed when instantiating a class.
In other words, the constructor is executed automatically just by creating a class.

How To Create Constructor

  1. function __construct(){}

So let's do it. Let's use the Car class we used earlier.
Do I have to start it up before the car can move?

  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()
  11. {
  12. echo "I started to run my car.";
  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. $honda = new Car;
  31. ?>

Result of the code above

In the code above, I didn't call any methods, I just created an instance.
When you create an instance, the constructor works automatically.
There is also a destructor.
Next time, let's look at the destructor. ^-^ *