是/为什么php会强制您使用对象构造函数

geo*_*y82 6 php oop object server

我一直在研究PHP中的对象.我见过的所有例子都使用了对象构造函数,甚至是他们自己的对象.PHP是否强迫您这样做,如果是这样,为什么?

例如:

<?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(); 
    ?>
Run Code Online (Sandbox Code Playgroud)

但如果我这样做:

<?php
class Person {
    public $isAlive = true;
    public $firstname;
    public $lastname;
    public $age;
}
$person->firstname = "John";
echo $person->firstname;
?>
Run Code Online (Sandbox Code Playgroud)

我得到一个http错误代码500.(即:我的代码崩溃).

ric*_*ck6 3

您错误地将__construct()函数与实例化类/对象的方式关联起来。

您不必使用__construct()功能(它是可选的)。但是,在使用类的方法之前,您必须先创建它的实例。

<?php
class Person {
    public $isAlive = true;
    public $firstname;
    public $lastname;
    public $age;
}
$person = new Person(); //Add this line
$person->firstname = "John";
echo $person->firstname;
?>
Run Code Online (Sandbox Code Playgroud)