SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Wizard DoubleDee's Avatar
    Join Date
    Aug 2010
    Location
    Arizona
    Posts
    3,777
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Preventing Undefined Error

    In order to prevent getting an Undefined Variable Error, I tend to do this a lot at the top of my scripts...
    PHP Code:
        $sessMemberID = (isset($_SESSION['sessMemberID']) ? $_SESSION['sessMemberID'] : '');

        
    $regEmail = (isset($_SESSION['registrationEmail']) ? $_SESSION['registrationEmail'] : ''); 

    Is there a more sophisticated approach?

    Thanks,


    Debbie

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,940
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    In PHP 5.3 you can do this:
    Code PHP:
    $variable = $item ?: NULL;
    There's a discussion of this here:http://stackoverflow.com/questions/4...n-if-not-empty

  3. #3
    PHP Guru lampcms.com's Avatar
    Join Date
    Jan 2009
    Posts
    921
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You are doing it the right way. Is there a more sophisticated approach? It depends on what you mean by sophisticated.
    You can write your own session handler class, register it with php as custom session handler and inside that class you can have a logic that would allow you to
    access any variable without ever generating an undefined notice.
    For example you can have your session class implement ArrayAccess interface and have a logic to return null when the actual property does not exist. This way if you
    do $var = $_SESSION['anyvar']; it will just set $var to null and will not raise a notice.
    This may be more sophisticated but it will not be more efficient as additional lines of code have to be processed.

    Anyway, you can also just abstract your current logic into a separate function, for example
    PHP Code:
    function getArrayVar(array $array$var){
    if(!
    array_key_exists($var$array){
    return 
    null;
    }

    return 
    $array[$var];


    Then you would get your var like this:

    $regEmail = getArrayVary($_SESSION, $regMail);

    This way you don't repeat your isset() ... logic.
    My project: Open source Q&A
    (similar to StackOverflow)
    powered by php+MongoDB
    Source on github, collaborators welcome!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •