What is the better way to write setter and getter in PHP? I mean, is better for a member class to have separate methods for getting and setting its value OR to have only one method for set and get?
Separate methods:
One method:
Why I'm asking this question? There are 2 reasons:
1- I have read at phpGirl a post entitled "Get it? Set it? Good!!" Where she asked the same question.
2- I'm starting to learn C# (Work necessity). In C# there is an elegant way for setter and getter:
So now if t is an instance of test, t.Count gets the value of the count member and t.Count = 10 sets the count member to 10. Just one entity to set and to get.
In PHP, I have always written 2 separate methods for setting and getting, but I think the way C# do it is elegant, although one method for both Set and Get in PHP is not wise. I think most PHP developers have to change their way of thinking to familiarize them selves with the "One Method" way if they want to go this direction. My personally preference in PHP is 2 methods which, I think, is the best suited for PHP-language. I haven't seen as I remember a PHP developer do it the "One Method" way.
What do you think ?
Separate methods:
class test {
private $count;
public function setCount( $value )
{
$this->count = $value;
}
public function getCount()
{
return $this->count;
}
}One method:
class test {
private $count;
public function Count( $value = "" )
{
if( empty( $value ) )
return $this->count;
else
$this->count = $value;
}
}Why I'm asking this question? There are 2 reasons:
1- I have read at phpGirl a post entitled "Get it? Set it? Good!!" Where she asked the same question.
2- I'm starting to learn C# (Work necessity). In C# there is an elegant way for setter and getter:
class test {
private int count;
public int Count
{
set { count = value; }
get { return count; }
}
}So now if t is an instance of test, t.Count gets the value of the count member and t.Count = 10 sets the count member to 10. Just one entity to set and to get.
In PHP, I have always written 2 separate methods for setting and getting, but I think the way C# do it is elegant, although one method for both Set and Get in PHP is not wise. I think most PHP developers have to change their way of thinking to familiarize them selves with the "One Method" way if they want to go this direction. My personally preference in PHP is 2 methods which, I think, is the best suited for PHP-language. I haven't seen as I remember a PHP developer do it the "One Method" way.
What do you think ?
07 Mar 2006 22:10:26
What about this http://www.dgx.cz/trine/ite... ?
19 Jan 2007 15:56:41
Hey cool site... if you can use PHP 5, it has two magic methods called __get() and __set()
which you can use like the following...in this case its easiest to internally use an array to store the values, but you can also use regular variables as below (this code isnt tested sorry may be bugs). Even easier than c# properties!
class Test {
private $var1;
private $var2;
public function __set($key,$val) {
$this->$key=$val;
}
public function __get($key) {
return $this->$key;
}
}
30 Apr 2007 11:46:49
John, good comment. but is there any way to make encapsulation code using __set or __get in terms some time there should be specific procedures to do during setting property or getting one?
30 Apr 2007 11:54:47
I though we can combine with allowed-empty-parameter-function as code below
class MyClass
{
private $prop1;
private $prop2;
public function __set($key, $val)
{
if ($key == "prop1")
Prop1Handler($val);
else
$this->$key = $val;
}
public function __get($key)
{
if ($key == "prop1")
return Prop1Handler();
else
return $this->$key;
}
private Prop1Handler($val == "")
{
if (empty($val))
return $this->prop1;
else
$this->prop1 = $val;
}
}
28 Aug 2007 00:47:42
Hello. I'm brazillian and now knowed this blog.And, my english is vary bad. hehehe.
I maked a function for getter and setter in my class. I called of "super magic getters/setters" because is used __get / __set with auto reflection to discovery your attributes of class.
see belong:
//SUPER GETTER MÁGICO
public function __get($property) {
if(array_key_exists($property,get_class_vars(__CLASS__))) {
return $this->$property;
} else {
die("<p>Método Getter inexistente da classe ".__CLASS__."<br>");
}
}
//SUPER SETTER MÁGICO
public function __set($property, $value) {
if (array_key_exists($property, get_class_vars(__CLASS__))) {
$this->$property = $value;
} else {
die("Método Setter inexistente da classe ".__CLASS__."<br>");
}
}
simple. But, for especific datas, I recommend metods separateds.
T+ (see later)
Mario junior
juninhog12||at||gmail||dot||com
31 Oct 2008 19:29:39
The One method is nice but not following code standard, because both empty return and return with value is used in the method. You should use overloading with __get and __set methods or use two separate methods.
29 Jan 2009 23:11:09
hello.
personally, i like to use separate functions for get and set.
however, if you want to use one function only, i believe, there should be no assumption of values to trigger the action.
for example, i you decide later, that "" is a valid value (clear the count), this breaks the application.
i suggest to test, if a parameter is given:
public function Count() {
if(func_num_args() == 0) {
return $this->count;
} else {
$this->count = func_get_arg(0);
}
}
.. if Count is called with a parameter, this is set to the member. if no parameter is provided, the current value is returned.
another point:
to mimic the standard php behaviour it might be nicer to actually return the value during set, too.
public function Count() {
if(func_num_args() != 0) {
$this->count = func_get_arg(0);
}
return $this->count;
}
regards,
thomas.
26 Mar 2009 02:14:36
I believe that you shouldn't write your code short-hand, it is more efficient and simpler to write the full script out. Or do what I've done and create a Class generator based off a database.
10 Apr 2009 09:39:52
your "one method" way is really wrong!
for example, you can't set the value to "", 0 or null !
see => http://www.php.net/manual/e...
You should never use the "one method" way.
(please mention this in your post)
29 Jun 2009 09:10:09
Hey,
i use something like this :
public function __get($key) {
//print("getter for |$key| <BR>");
switch($key) {
case "page_title":
case "wintitle":
return $this->_page_title;
break;
default:
return $this->{$key};
}
}
public function __set($key, $value) {
//print("setter for $key <BR>");
switch($key) {
case "page_title":
// do something
$this->_page_title=$value;
break;
default:
$this->{$key}=$value;
break;
}
}
it's a kind of a hassle not having getter and setter for each key, so you must have a switch in the get and the set function, but ... at least it works :)
06 Oct 2009 22:34:28
The __get and __set come close to defeating the purpose of getters and setters. The main reasons for using getters/setters instead of public vars is to (1) control which vars can be got/set, and (2) to control what goes into and out of them. With C# I have to explicitly define my getters/setters, which forces me to think about it. With __get/__set the default behavior is to leave my internal vars open to the public unless I code otherwise!
In short, I don't like it. I'll explicitly code my own get/set methods until PHP provides real ones.
05 Jan 2010 23:54:26
Since some classes are full of getters/setters (usually getters) that just read the variable, there are times when this default behavior makes sense.
If you were going to do it that way, though, what I'd do is make the variables in question public, use __set to make them read only, then put in a __get method if you ever find you need to interrupt the retrieving behavior.
If your __set could get at all complicated, I'd plan for dedicated setters instead. It will read better.
09 Feb 2010 17:36:08
its better to just use normal get set functions to preserve integrity of the variables - as in java.
there is a site <a href="http://www.icurtain.co.uk/g...">http://www.icurtain.co.uk/getset.php<a/> that shows you how to do it
21 Feb 2010 03:10:18
I have always had a problem with OOP purist who say you even need a getter and setter for situations like the first example. If all you are doing is setting and getting a variable, even if the class updates it between getting and setting, just make it a public variable.
getters and setters are more for when you want to do something programmatic when you set a value. So, for instance, if you provide a date string and the setter function splits it into month,day, year, hours, minutes, and seconds. Or you are getting a value that is derived from say a call to a database table or twelve. getters and setters are functions that look like variables.
Lastly, the more interesting use of getters and setters is for creating read or write-only 'variables'. A variable that only has a getter is read-only. A variable that only has a setter is write only.
However, for the original use case presented in this post
class test{
$count = 0;
function Increment($val=1) {
$this->count += $val;
}
function Decrement($val=1) {
$this->count -= $val;
}
function Reset() {
$this->count = 0;
}
}
$tester = new test();
echo($tester->count);
// echos '0'
$tester->Increment(2); // count = 0 +2 = 2
$tester->Increment(); // count = 2 + 1 = 3
echo($tester->count);
//echoes '3';
$tester->count= 42;
echo $tester->count;
// echos '42'
$tester->Decrement(); // count = 42-1 = 41
echo $tester->count;
// echos '41'
$tester->Reset();
echo $tester->count;
// echos '0'
No getters or setters, just functions for manipulating the value in some normal action. If you need to set the counter specifically you can, and you can get it. There's no reason for a getter or setter.
If, however, you decided you wanted to make sure that the count didn't go above or below a certain value, then a setter would be needed for taking in the value and comparing it against min/max values. Then increment and decrement should use that setter when changing the value. But if you are not doing anything like that, just use a public variable.
29 Jun 2010 06:54:51
Hi everybody !
I come from Belgium and I worked during 2years in .Net specifically in ASP.Net with C#, now I'm working in PHP.
The way to do getter and setter in one method is very powerful. In C# it's very simple and it's faster than 2 methods.
When I use PHP, I prefer and I like to keep this single method. I think it's more easy and clearer for the coed than 2 separated methods.
Jisay