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
oztech
Forum Newbie
Posts: 11 Joined: Thu Dec 04, 2008 6:58 pm
Post
by oztech » Thu May 07, 2009 4:02 pm
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~~~
requinix
Spammer :|
Posts: 6617 Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA
Post
by requinix » Thu May 07, 2009 4:14 pm
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
Post
by oztech » Thu May 07, 2009 4:26 pm
So what's the difference??
Christopher
Site Administrator
Posts: 13596 Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US
Post
by Christopher » Thu May 07, 2009 8:05 pm
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)