Basic OOP ...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
oztech
Forum Newbie
Posts: 11
Joined: Thu Dec 04, 2008 6:58 pm

Basic OOP ...

Post 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~~~
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Basic OOP ...

Post 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
oztech
Forum Newbie
Posts: 11
Joined: Thu Dec 04, 2008 6:58 pm

Re: Basic OOP ...

Post by oztech »

So what's the difference??
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Basic OOP ...

Post 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'
(#10850)
Post Reply