Page 1 of 1

which one to use and why ??

Posted: Tue Jul 03, 2007 5:56 am
by PHPycho
Hello forums!!
I am curious about some question which i am going to mention here.
we know the advantage of using getters and setters in OOP.
Let us consider the case:

Code: Select all

<?php
class className{
	var prop1;
	var prop2;
	var prop3;
	
	function className(){
		// Empty constructor
	}
	
	function setProp1($prop1){
		$this->prop1 = $prop1;
	}
	function getProp1(){
		return $this->prop1;
	}
	function setProp2($prop2){
		$this->prop2 = $prop2;
	}
	function getProp2(){
		return $this->prop2;
	}	
	function addProp12(){
		$value = $this->prop1 + $this->prop2;
		// Alt $value = $this->getProp1() + $this->getProp2();
		return $value;
	}
}

// Using Class
$classObj = new className();
$classObj->setProp1("x");
$classObj->setProp2("y");
echo $classObj->addprop12();
?>
My Question is very simple..
once the property is set using methods, for internal use in the class file
which one to use and why ?
1> $value = $this->prop1 + $this->prop2;
2> $value = $this->getProp1() + $this->getProp2();

Thanks in advance to all of you.

Posted: Tue Jul 03, 2007 6:09 am
by onion2k
Makes no difference. Go with whichever style you find more readable.

Posted: Tue Jul 03, 2007 6:17 am
by Gente
There is another note. I don't think that it's a good idea to put the code outside class declaration in the class file.

Posted: Tue Jul 03, 2007 6:50 am
by superdezign
Gente wrote:There is another note. I don't think that it's a good idea to put the code outside class declaration in the class file.
To extend on that, the reason is that if you don't use include_once, that code will run more than once. Beyond that, there's not that much wrong with it, beside it being... unorthodox.

Posted: Tue Jul 03, 2007 7:24 am
by volka
And there's nothing wrong with keeping the example simple that way.


You might find http://www.ibm.com/developerworks/webse ... -accv.html and http://www.javaworld.com/javaworld/jw-0 ... tml?page=1 interesting.