Jump to content

[SOLVED] Problem with objects starting value.


Foser

Recommended Posts

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?

 

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);

?>

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.