Page 1 of 1

Basic OOP ...

Posted: Thu May 07, 2009 4:02 pm
by oztech
Hi, I'm pretty new to OOP in PHP. However, I'm not sure why the below code don't work. Please give kind advise!

***** Please add

Code: Select all

tag when posting source *****[/color]

Code: Select all

class Dateinfo {
    
        public $year, $month, $day;
        
        function __construct($p_year, $p_month, $p_day){
            $this->$year = $p_year;
            $this->$month = $p_month;
            $this->$day = $p_day;
        }
        
        function __get($name){
            return $this->$name;
        }
        
        function __set($name, $value){
            $this->$name = $value;
        }
        
        function getToday(){
            $today = $this->$year."-".$this->$month."-".$this->$day;
            return $today;
        }
    }
 
$dateinfo = new Dateinfo(date('Y'), date('m'), date('d'));
print_r($dateinfo->getToday());
 
above prints "--"
Please help~~~

Re: Basic OOP ...

Posted: Thu May 07, 2009 4:14 pm
by requinix
When using -> the member variable name should not have a dollar sign.

Code: Select all

$this->$year = 2009; // bad, completely different meaning
$this->year = 2009;  // good

Re: Basic OOP ...

Posted: Thu May 07, 2009 4:26 pm
by oztech
So what's the difference??

Re: Basic OOP ...

Posted: Thu May 07, 2009 8:05 pm
by Christopher
oztech wrote:So what's the difference??

Code: Select all

class Dateinfo {
     public $year;
     public $month;
}
 
$foo = new Dateinfo;
$value = 'month';
 
$foo->year = '2009';       // sets the year property
$foo->$value = '2009';      // sets the month property because $value contains 'month'