which one to use and why ??

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
PHPycho
Forum Contributor
Posts: 336
Joined: Fri Jan 06, 2006 12:37 pm

which one to use and why ??

Post 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.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

Makes no difference. Go with whichever style you find more readable.
User avatar
Gente
Forum Contributor
Posts: 252
Joined: Wed Jun 13, 2007 9:43 am
Location: Ukraine, Kharkov
Contact:

Post 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.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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.
Post Reply