Ho fatto delle ricerche sugli oggetti in PHP. Tutti gli esempi che ho visto usano il costruttore di oggetti anche sui propri oggetti. PHP ti obbliga a farlo e se sì perché?Fa/Perché php ti costringe a usare il costruttore di oggetti
Ad esempio:
<?php
class Person {
public $isAlive = true;
public $firstname;
public $lastname;
public $age;
public function __construct($firstname, $lastname, $age) {
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->age = $age;
}
public function greet() {
return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
}
}
// Creating a new person called "boring 12345", who is 12345 years old ;-)
$me = new Person('boring', '12345', 12345);
echo $me->greet();
?>
Ma se faccio questo:
<?php
class Person {
public $isAlive = true;
public $firstname;
public $lastname;
public $age;
}
$person->firstname = "John";
echo $person->firstname;
?>
ottengo un codice di errore HTTP 500 (vale a dire: Il mio codice è caduto).