Nicolas
Nicolas

Reputation: 601

symfony2 best way to test/get a session attribute

I do this to test and get session attribute in my code :

if ($session->has("myVar")) {
    $myVar = session->get("myVar");
    /* do something */ 
}

But, I read the code of session and :

 /**
 * Returns an attribute.
 *
 * @param string $name    The attribute name
 * @param mixed  $default The default value if not found.
 *
 * @return mixed
 *
 * @api
 */
public function get($name, $default = null);

So, if the session attribute is not find, get return "null".

if ($myVar = $session->get("myVar")) {
    /* do something */    
}

Or better with false, if you have "myVar" but empty, you can't rely on "null" :

if ($myVar = $session->get("myVar", false)) {
    /* do something */    
}

according to : Null vs. False vs. 0 in PHP

I think the third is the best, one call to $session->get, instead of has and get in my actual code.

I read about alternative comparaison with ternary operator, http://fabien.potencier.org/article/48/the-php-ternary-operator-fast-or-not, I don't use it, mostly because I.m not familiar with, but, if it's not faster, I don't need it.

Can you confirm, third is the best, and if it's not, why, and how to do best ?

Upvotes: 3

Views: 3686

Answers (1)

DerStoffel
DerStoffel

Reputation: 2633

That depends on what you want to achieve.

First Option

if ($session->has("myVar")) {
    $myVar = session->get("myVar");
    /* do something */ 
}

Makes sense if you want to make sure, that this var is set, and if not you actually want to set it or do anything else. It presumes that having this session variable present is a necessity

Second Option

$myVar = $session->get("myVar");

This one makes sense, if you are comfortable receiving the expected result or a null value as default if not set.

Recommendation:

$myVar = $session->get("myVar");
if (null === $myVar) {
    /* do something */    
}

Third Option

$myVar = $session->get("myVar", false);

This one simply allows you to override the default value if this session variable is not set

Recommendation:

$myVar = $session->get("myVar", false);
if (!$myVar) {
    /* do something */    
}

So, in my opinion it depends what you want to do. But there is no best or worst way as you asked for, since they all differ from each other.

Upvotes: 4

Related Questions