Foser Posted December 16, 2007 Share Posted December 16, 2007 I'm new to OOP so i decided to do a tutorial but there seems to be an issue. <?php class Rectangle { var $width; var $height; function Rectangle($width, $height){ $this->width; $this->height; } function area(){ return $this->width * $this->height; } } $myRectangle = new Rectangle(10,20); echo $myRectangle->area(); ?> out of this i get an area of "0" which is false. because the width is 10 and the height is 20. Although when i give the values to it like: $myRectangle->width = 10; $myRectangle->height = 20; then it will work. am I doing something wrong? Quote Link to comment https://forums.phpfreaks.com/topic/81878-solved-problem-with-objects-starting-value/ Share on other sites More sharing options...
pocobueno1388 Posted December 16, 2007 Share Posted December 16, 2007 You need a construct function <?php class Rectangle { var $width; var $height; function __construct($width, $height){ $this->width = $width; $this->height = $height; } //...the rest of the class code here } $myRectangle = new Rectangle(10,20); ?> Quote Link to comment https://forums.phpfreaks.com/topic/81878-solved-problem-with-objects-starting-value/#findComment-416038 Share on other sites More sharing options...
redbullmarky Posted December 17, 2007 Share Posted December 17, 2007 poco, looking at Foser's original code, he already has a valid constructor (method with same name as class) - __construct is PHP5 only, but the named constructor works for both 4 and 5. the problem i can see is you're not actually assigning the values to the object properties. instead of just $this->width; $this->height; you need $this->width = $width; $this->height = $height; so: <?php class Rectangle { var $width; var $height; function Rectangle($width, $height){ $this->width = $width; $this->height = $width; } function area(){ return $this->width * $this->height; } } $myRectangle = new Rectangle(10,20); echo $myRectangle->area(); ?> should do the trick hope that helps Cheers Mark Quote Link to comment https://forums.phpfreaks.com/topic/81878-solved-problem-with-objects-starting-value/#findComment-416646 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.