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

时间:2015-07-24 22:13:16

标签: php class oop object

这是类文件:

<?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方法?我想确保使用正确的编码实践,所以即使我可以在没有构造的情况下使用公共方法/变量,我也更愿意这样做。

1 个答案:

答案 0 :(得分:1)

修改

我刚刚意识到你的_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;
}
}