Kyle Birch
Kyle Birch

Reputation: 75

PHP: error obtaining data from object with get method

Here is the class file:

<?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;
}
}

Here is the script calling the class file:

<?php
require $_SERVER['DOCUMENT_ROOT'] . '/classes/user.php';
$user1 = new     user('Kyle','Birch','birchk1','[email protected]','195822Kb');
echo $user1->getFirstName() . ' is the first name';

Here is the error and display as a result:

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

Why isn't this calling the get method properly? I want to make sure I use proper coding practices, so even though I could just use public methods/variables without constructs, I prefer to do it properly.

Upvotes: 0

Views: 43

Answers (1)

Mikhail Levkovsky
Mikhail Levkovsky

Reputation: 86

EDIT

I just realized that your _construct function only has one "_", it needs two underscores: "__" to be syntactically correct

For good OOP practices you need to add the variables as class variables:

<?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;
}
}

Upvotes: 1

Related Questions