Search code examples
phpconstructorgetter-setter

How to call Constructors from other Pages in PHP


I am trying to call an object from a class located in another PHP file as so:

Login.php

        $user  = new LoginClass($usernameEntered); //where usernameEntered is just some form data that was submitted
        $user->login();
        echo "User: " .$user->getUser();

And the class:

class LoginClass
{
private $theUser="Default";

public function _construct($user)
{
    $this->theUser=$user;
}
public function login()
{
   // $this->theUser=$user;
    echo "I am in login with ". $this->theUser;
    session_start();
    $_SESSION["user"] = serialize($this);
    setcookie("user",$this->theUser,time() + (86400 * 30));
}
public function logout()
{
    session_destroy();
}
public function getUser()
{
    return $this->theUser;
}
}

The weird issue I am having is that if I move the $this->theUser=$user; to the login method everything works, however if I leave the code as is, Login.php never seems to call the constructor and $theUser variable is never set(that is it prints out "Default"). Is there some other way I should be calling class constructors so I can set these values in the constructor?


Solution

  • You miss 1 underscore!

    It's __construct() not _construct()!