我一直在研究 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();
?>
但是如果我这样做:
<?php
class Person {
public $isAlive = true;
public $firstname;
public $lastname;
public $age;
}
$person->firstname = "John";
echo $person->firstname;
?>
我收到一个 HTTP 错误代码 500。(即:我的代码崩溃了)。
最佳答案
您错误地将 __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;
?>
关于php - 是否/为什么 php 强制您使用对象构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30485048/