PHP:使用get方法从对象获取数据出错


PHP: error obtaining data from object with get method

下面是类文件:

<?php
class user{
function _construct($firstName, $lastName, $username, $email, $password){
    $this->firstName    = $firstName;
    $this->lastName     = $lastName;
    $this->username     = $username;
    $this->email        = $email;
    $this->password     = $password;
}
public function getFirstName(){
    return $this->firstName;
}
public function getLastName(){
    return $this->lastName;
}
public function getUsername(){
    return $this->username;
}
public function getEmail(){
    return $this->email;
}
public function getPassword(){
    return $this->password;
}
}
下面是调用类文件的脚本:
<?php
require $_SERVER['DOCUMENT_ROOT'] . '/classes/user.php';
$user1 = new     user('Kyle','Birch','birchk1','theflyinginvalid@gmail.com','195822Kb');
echo $user1->getFirstName() . ' is the first name';

下面是错误和显示结果:

Notice: Undefined property: user::$firstName in /Applications/XAMPP/xamppfiles/htdocs/classes/user.php on line 13
is the first name

为什么不能正确调用get方法?我想确保我使用了正确的编码实践,所以即使我可以只使用公共方法/变量而不使用结构,我也更喜欢正确地使用它。

EDIT

我刚刚意识到你的_construct函数只有一个"_",它需要两个下划线:"__"语法正确

对于良好的OOP实践,您需要将变量添加为类变量:

<?php
class user{
protected $firstName;
protected $lastName;
protected $username;
protected $email;
protected $password;
function __construct($firstName, $lastName, $username, $email, $password){
    $this->firstName    = $firstName;
    $this->lastName     = $lastName;
    $this->username     = $username;
    $this->email        = $email;
    $this->password     = $password;
}
public function getFirstName(){
    return $this->firstName;
}
public function getLastName(){
    return $this->lastName;
}
public function getUsername(){
    return $this->username;
}
public function getEmail(){
    return $this->email;
}
public function getPassword(){
    return $this->password;
}
}