...

View Full Version : Problem echoing a variable in OOP



MHaris
08-22-2007, 02:35 AM
<?php

class Tree{

private $_Type;
private $_Height = 1;

public function setType($_TheType){
$_Type = $_TheType;
echo '<b>'.$_Type.' tree has been cultivated.</b><br/>';
echo 'The height of '.$_Type.' Tree is '.$this->_Height.' meters<br/>';
}

public function oneYearPasses(){
$this->_Height++;
echo 'The'.$this->_Type.' grows to '.$this->_Height.' meter <br/>';
}

}

$OrangeTree = new Tree;
$OrangeTree->setType('Orange');
$OrangeTree->oneYearPasses();

$AppleTree = new Tree;
$AppleTree->setType('Apple');
$AppleTree->oneYearPasses();

$MangoTree = new Tree;
$MangoTree->setType('Mango');
$MangoTree->oneYearPasses();
?>

Why doesn't oneYearPasses method echo's the $_TYPE in the echo? echo 'The'.$_Type.' grows to '.$this->_Height.' meter <br/>';

PappaJohn
08-22-2007, 02:48 AM
$_Type = $_TheType;
should be

$this->_Type = $_TheType;

A better way to do this:



<?php

class Tree{

private $_Type;
private $_Height = 1;

public function setType($_TheType){
$_Type = $_TheType;
$return_val = '<b>'.$_Type.' tree has been cultivated.</b><br/>';
$return_val .= 'The height of '.$_Type.' Tree is '.$this->_Height.' meters<br/>';

return $return_val;
}

public function oneYearPasses(){
$this->_Height++;
$return_val = 'The'.$this->_Type.' grows to '.$this->_Height.' meter <br/>';

return $return_val;
}

}

$OrangeTree = new Tree;
echo $OrangeTree->setType('Orange');
echo $OrangeTree->oneYearPasses();

GJay
08-22-2007, 02:49 PM
returning rather than echoing is often a better idea, but losing the constructor in place of a setter doesn't really make sense in this case, it allows you to change the type of the tree as many times as you like!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum