phpoopsessionconstruct

PHP - need an assits with __construct()


So I have this PHP code that I don't get

public $user = 'guest';

public function __construct()
{
    $this->user = (isset($_SESSION['user'])) ? $_SESSION['user'] : 'guest';
}

Can anyone please explain the above code , and is there any chance that I can change the session value without accessing the server-side ?


Solution

  • Incoming request is being handled by script on server (it's a PHP as splash58 pointed out)

    __construct() creates new objects, and inside it's decided if there is no user already set inside session ($_SESSION superglobal array), it injects 'guest' value into $this->user.

    It's basically saying "if user did not log in, he's a guest".

    You cannot change $_SESSION contents from frontend, this is done on server-side, so you have to modify PHP script to apply changes.

    Edit: for clarification, what you see inside constructor is ternary operator. Documentation here: https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary