Jump to content

Recommended Posts

Posted (edited)

Hello,

I'm working through the login System using OOP in Stef's course.  In the file m_template.php, there is this line of code:

(Line 58)

function setAlert($value, $type = null)
    {
        if ($type == '') { $type = $this->alertTypes[0]; }
        $_SESSION[$type][] = $value;
    }

I'm trying to see how the highlighted section of code is working.

Ben explains this, but I don't quite understand yet.

First of all, I want to check that my concept of the session variable $_SESSION is correct:

If I unpack a hypothetical $_SESSION variable, it could look something like this:

$_SESSION [

'success' => ['you are logged in']

'warning' =>[ ]

'error' => []

user => 'John'

]

So, $_SESSION is a variable holding an array.  Within that array is another array which could have a key of either success, warning, or error.

$_SESSION might also have other elements in the array like user.

When I write the code $_SESSION[$type][] = $value; I could think of it in this example:

$_SESSION['success'][] = 'you are logged in';

This line of code means that I will be adding to the nested array with the key of 'success'.

So if $_SESSION looked like this instead:

$_SESSION [

'success' => ['logging in is awesome', 'You are so bomb for logging in', 'High Five!', ]

'warning' =>[ ]

'error' => []

user => 'John'

]

I would be tacking on 'you are logged in' like so:

'success' => ['logging in is awesome', 'You are so bomb for logging in', 'High Five!',  'you are logged in']

However, if I left out the brackets like so:

$_SESSION['success'] = 'you are logged in';

then I would over-write the array with the key of 'success' and create this:

'success' => 'you are logged in'

Am I thinking about all of this correctly?

Update: Nov 11, 2020

I wonder if it is a bit unnecessary to have this line of code:

$_SESSION[$type][] = $value (m_template.php, line 58)

rather than this:

$_SESSION[$type]= $value

There doesn't seem to be any circumstance where there is more than one value per key at any given time.

 

 

Edited by Drew2
  • 1 month later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...