Domanda

In Ruby, I wouldn't define variables prior to the constructor. Tutorials in PHP suggest that I do, though it seems to work when I don't.

What benefit does this approach provide? Is there a difference between the Ruby function initialize and the PHP function __construct?

class ConnectToDatabase {

  public $host;
  public $user;
  public $password;
  public $database;

  function __construct($host, $user, $password, $database) {
    $this->host = $host;
    $this->user = $user;
    $this->password = $password;
    $this->database = $database;
  }
}
È stato utile?

Soluzione 2

In general defining the classes member variables outside of the member functions provides a few benefits.

They clearly indicate what is intended to be a member variable. This is not to be underestimated. Other developers, and even yourself in 5 months, will want to know what are the member variables. If one has to hunt through the member functions of the class, one may miss a variable. In any case, it would take longer to find.

Also, any code completion your IDE will be using, will probably not be able to pick up the member variables if they are only declared in the constructor.

Finally, you can override the constructor. In that case, those member variables may not be available.

FROM @meager: An important one; "You can change them from public to private, and you can initialize them with static values."

Altri suggerimenti

What benefit does this approach provide?

You can change them from public to private, and you can initialize them with static values.

Is there a difference between the ruby function initialise and the php function __construct?

Yes, they are very different. They aren't really comparable; Ruby and PHP's object model is too different.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top