Accessing Object in an Array

Discussion in 'PHP' started by absentx, Nov 14, 2011.

  1. #1
    Hello all, I need a little help accessing an object that is in an array.

    I know my array is holding objects because I have tested with var_dump

    So, this returns an error..I have learned that we cannot access an object using the subscript operator:

    
    
     $foo = $neat_array[$i+1]->format('U') ; //looking to format DateTime object as unix
    
    returns fatal error Call to a member function format() on a non-object
    
    
    PHP:
    Okay, I except my defeat, and now realize that I must access using ->

    But so far nothing I have tried works. How do I access [$i] or any specific value in the array without using subscript and instead using ->???

    Thanks, just beginning to try the Object oriented stuff.
     
    absentx, Nov 14, 2011 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,899
    Likes Received:
    4,555
    Best Answers:
    123
    Trophy Points:
    665
    #2
    It looks like it should work but while you are nutting it out try breaking it down a bit more (then build it back up)

    $counter = $i + 1;
    $obj = $neat_array[$counter];
    var_dump($obj);
    if (method_exists($obj, 'format') $foo = $obj->format('U');
    else $foo = false;
    var_dump($foo);
    PHP:
    Painful, but useful

    My next concern would be that "format" is a protected word, so you may be better to create a new method called formatU which doesn't then need the parameter. Could be a red herring though.
     
    sarahk, Nov 14, 2011 IP
  3. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #3
    Can you var_dump or print_r the $neat_array? It should help fully understand how to access it.
     
    jestep, Nov 15, 2011 IP
  4. absentx

    absentx Peon

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Hi guys, thanks for the help.

    Ultimately my problem was that my counter was going one too far, trying to access an element of the array which didn't exist, and then trying to format that non-existent element.

    Breaking it down finally allowed me to see that it indeed was processing most of the array but breaking on the last loop because the element didn't exist.

    Thanks for the help.
     
    absentx, Nov 15, 2011 IP