php - symfony2 best way to test/get a session attribute -


i test , session attribute in code :

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

but, read code of session , :

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

so, if session attribute not find, return "null".

if ($myvar = $session->get("myvar")) {     /* */     } 

or better false, if have "myvar" empty, can't rely on "null" :

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

according : null vs. false vs. 0 in php

i think third best, 1 call $session->get, instead of has , in actual code.

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

can confirm, third best, , if it's not, why, , how best ?

that depends on want achieve.

first option

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

makes sense if want make sure, var set, , if not want set or else. presumes having session variable present necessity

second option

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

this 1 makes sense, if comfortable receiving expected result or null value default if not set.

recommendation:

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

third option

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

this 1 allows override default value if session variable not set

recommendation:

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

so, in opinion depends want do. there no best or worst way asked for, since differ each other.


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -