I am new to php and OOP in general, so have decided to turn my existing site in an oo php one to gain some experience.
Here is the issue I am currently facing.
I have a class Normaluser which is extending from User. Inside the User class is a login method which returns an object containing an array of the Users class’ properties.
class NormalUser extends User {
public function __construct($loginarray){
$email = $loginarray['email'];
$pass = $loginarray['pass'];
var_dump ( parent::login($email,$pass) );
//return parent::login($email,$pass)
}
}
When doing a var_dump (as above) I get
bool(false) object(User)#8 (4)
{ ["user_id"]=> string(1) "1" ["first_name"]=> string(7) "Melanie" ["last_name"]=> string(6) "Janson" ["user_level"]=> string(1) "1" }
Yet after calling the code in my login.php page :
$postdata = User::mysqli_array_escape($_POST);
$email = $postdata['email'];
$pass = $postdata['pass'];
$userstart = new NormalUser($postdata);
var_dump($userstart);
I would think that calling $userstart as a new NormalUser object would return the correct variables, yet when I do a var_dump (as written in above) I receive the following :
object(NormalUser)#5 (4)
{ ["user_id"]=> NULL ["first_name"]=> NULL ["last_name"]=> NULL ["user_level"]=> NULL }
I do not understand where I have gone wrong, If anyone would be able to point me in the right direction I would be greatly appreciative.
Thank you.
EDITED : added user.php login method as requested
public static function login($email, $pass) {
global $database;
$sql = "SELECT user_id, first_name, last_name, user_level FROM users WHERE (email='$email' AND pass=SHA1('$pass')) AND active IS NULL LIMIT 1";
$results = self::find_by_sql($sql);
//var_dump($results);
if (!empty($results)) {
return array_shift($results);
} else {
return false;
}
}
The problem is that you are returning an object in the constructor. This is not how constructors work.
I have two options for you:
Either you create a static method that returns a NormalUser instance (instead of using the constructor):
Or you stick with the constructor but instead of returning an object instance, you assign its attributes to the
$thisinstance: