0

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

Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378

3 Answers3

1

I added the function before your __construct, but other than that it seems to work fine

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

$m = new myclass();
echo $m->getProp('info');

// echos 'nothing'
Aaron W.
  • 9,254
  • 2
  • 34
  • 45
1

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');
Paul
  • 139,544
  • 27
  • 275
  • 264
  • Haha yeah, almost the same time too. Funny that I chose to put backticks around `__construct` and you chose to put them around `function`. – Paul May 31 '12 at 22:00
0

I think you should read up on PHP's magic methods. What you're doing is very possible, but the way you're doing it is perhaps not the best.

http://php.net/manual/en/language.oop5.magic.php

I think you should be looking at the __get() and __set() methods.

vicTROLLA
  • 1,554
  • 12
  • 15