Search code examples
phpobjectprotected

get protected attribute by parameter referencing name?


lets say:

class myclass{
     protected $info;
     protected $owner;
     __construct(){
        $this->info = 'nothing';
        $this->owner = 'nobody';
    }
    function getProp($string){
        return $this->$string;
    }
}

But its not working, is it not posible? its not returning anything or showing errors


Solution

  • It works fine, but you're missing the function keyword in front of __construct. This outputs "nothing":

    <?php
    
    class myclass{
         protected $info;
         protected $owner;
    
        function __construct(){
            $this->info = 'nothing';
            $this->owner = 'nobody';
        }
        function getProp($string){
            return $this->$string;
        }
    }
    
    $test = new myclass();
    echo $test->getProp('info');