Get protected data

Discussion in 'PHP' started by Fracisc, Oct 10, 2016.

  1. #1
    I have this:

    
    Array
    (
        [0] => afprg Object
            (
               
    
                [id:protected] => 882
    
                            )
    
                    )
    
            )
    
    PHP:
    How can I print all the id's?

    Thanks!
     
    Fracisc, Oct 10, 2016 IP
  2. edduvs

    edduvs Well-Known Member

    Messages:
    394
    Likes Received:
    31
    Best Answers:
    3
    Trophy Points:
    160
    #2
    Can you show us a bit more context ? That's by far not enough.
     
    edduvs, Oct 10, 2016 IP
  3. Einheijar

    Einheijar Well-Known Member

    Messages:
    539
    Likes Received:
    13
    Best Answers:
    3
    Trophy Points:
    165
    #3
    Go to the class and redefine it as public
     
    Einheijar, Oct 11, 2016 IP
    ThePHPMaster likes this.
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    That array isn't gonna return anything - or at least it shouldn't. The syntax is FUBAR.
     
    PoPSiCLe, Oct 11, 2016 IP
  5. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #5
    Like Einheijar mentioned, the best and the correct way is to set the variable public at declaration level or add a getter method within the object. If that isn't an option (not sure why it wouldn't) you can use reflection to get value:

    
    <?php
    class afprg {protected $id = 'test';}
    $a = array(new afprg());
    print_r($a); // Similar to what you had
    
    foreach ($a as $object) {
        $rp = new ReflectionProperty('afprg', 'id');
        $rp->setAccessible(true);
        echo $rp->getValue($object);
    }
    
    PHP:
     
    ThePHPMaster, Oct 11, 2016 IP
  6. edduvs

    edduvs Well-Known Member

    Messages:
    394
    Likes Received:
    31
    Best Answers:
    3
    Trophy Points:
    160
    #6
    That moment when you see lowercase named classes wrapped inside an array... that's when I know I have to unwatch the thread :)
     
    edduvs, Oct 11, 2016 IP