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?

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.