我一直在研究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)