A
A
Anton R.2019-08-14 11:29:21
PHP
Anton R., 2019-08-14 11:29:21

Why declare (create) field names at the beginning of the class if they are in fact declared (created) in the constructor?

For example, here is the code:

<?php
class Testclass{
  
  private $a;
  private $b;
  
  public function __construct($a, $b){
    $this->a = $a;
    $this->b = $b;
  }
}

In the constructor, we set the values ​​of the variables $a and $b, but even if I remove the first two lines of private $a; private $b; at the beginning of the class, then these fields will be automatically created from the constructor and the internal method will work fine:
class Testclass{
  
  //Закомментировал private $a;
  //Закомментировал private $b;
  
  public function __construct($a, $b){
    $this->a = $a;
    $this->b = $b;
  }
  public function Sum(){
    echo $this->a + $this->b;
  }
}
  
$object = new Testclass(5, 6);
$object->Sum();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rfm, 2019-08-14
@anton_reut

so that in the code editor when you type
$object->|
he could tell you what properties an object has.
to explicitly indicate the visibility of properties (for example, protected)
so that later you do not look for what properties the object has in a year, rummaging through all its methods.
so that everything doesn’t fall off for you if you rewrite the constructor in the descendant class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question