the purpose of using the setter and getter method? - php

I understand the code flow but I never use them because I don't know what is it for.. can you show me a practical way of using it?
the purpose of setter and getter method ?
<?php
class person {
var $name;
function set_name($new_name) {
$this->name = $new_name;
}
function get_name() {
return $this->name;
}
}
?>

For trivial cases like this one, the getter and setters are frankly useless except for a strict interpretation of the Encapsulation Principle (which I endorse anyway).
They become useful when accessing a variable has side effects to be tracked or a variable that shouldn't be handled directly by the user but only through a strict, defined procedure: for example a global counter in a multithread environment.
Another useful aspect of a setter method is a validation of the data: let's say that the variable can hold only odd numbers greater than 100 and smaller than 200. Without a setter i can place any value I want, with the setter i can sanitize the input inside the object itself rather than outside.
All said, you should always use getters and setters. They might get handy in the future.

Thue purpose of getter setter methods are mainly in Data Tranfer Objects(DTO) , beans etc where we want to transport objects with values from one layer to another

The purposes are different in both languages:
in Java, setters and getters are part of the "Java Bean" standard, and serve to define public properties (properties are - by definition - things exposed as getters and setters); a lot of IDEs, wizards and libraries expect such methods (which, by the way, is a widely useful and equally misunderstood abstraction).
in PHP they are less useful, but they do make it easier to control the type of an attribute (you can have type hints on methods and you can't have them on attributes)
in PHP and Java they let you make certain things "write only"
in PHP and Java they help people using IDEs in guessing "how to configure this object" - usually you can just type set, press ctrl+space and browse the configurable stuff.
in both languages they add a bit of encapsulation and help in guarding your code against change (which is - arguably - less important in PHP, where you could use a magic __get method anyway).
Mostly, they are just question of style and uniformity.

One advantage is you can use getters and setters to control values as they come in:
<?php
class car{
var $engineSize;
function setEngineSize($size) {
if($size > 0){
$this->engineSize = $size;
}
}
?>

The getter and setter methods gives you centralized control on how a particular field is initialized, accessed and provided to client which makes validation and debugging much easier. You can simply put a breakpoints or print statement to see which threads are accessing and what values are going out.

Related

What is the point of OOP visibility in PHP when Closures and Reflections are available?

Consider this code here:
final class TinkerWithMe {
protected $key1 = 19;
private $key2 = 88;
}
$class = new TinkerWithMe();
$getKeys = function() {
return array($this->key1, $this->key2);
};
$oldKeys = $getKeys->call($class);
$newKey1 = 96;
$newKey2 = 42;
$setKeys = function() use ($newKey1, $newKey2) {
$this->key1 = $newKey1;
$this->key2 = $newKey2;
};
$setKeys->call($class);
Why bother with OOP visibility when you can get around it so easily with Closures or Reflections?
Is there a way of blocking this kind of thing that I am missing?
Visibility modifiers aren't iron clad protection or ensure any sort of security or anything of that sort. They're markers for how a piece of code is intended to be used.
When writing a piece of code like a class, other pieces of code are going to couple with it; meaning you will write other code that calls methods of that class or accesses properties of that class. In order to minimise coupling to the absolute necessary, you will want to keep the public interface of the class as small as possible. When you designate something as public, you're marking it "for general use". That public piece should then be rather stable and not change, or you risk breaking a lot of coupled code if you do change it.
Marking something as protected or private marks these parts as not for general consumption; it clarifies that these implementation details might change in the future or are not supposed to be used by other code "not in the know". This allows you to easier refactor those parts later as necessary and having a better idea of what other parts might break as a result. It also helps to ensure the internal state of the class is consistent when external code won't directly modify internal values without completely understanding how it should do so.
PHP will help you honour those markers in the general case by throwing errors when naïvely trying to access protected or private properties "from the outside"; that prevents most accidental usage and unwanted coupling. PHP is not going to bend over backwards to ensure those properties stay inaccessible under all possible circumstances. If you're really bent on shooting your own foot, so be it. Perhaps you need to do so for testing purposes; it would be counter productive to absolutely prevent you from doing so.
In the mantra of Python:
We're all consenting adults here.
Great question! I would like to add few more points
The purpose of specifying visibility in OOP languages is:
To show what the properties and methods are meant to do. This is to bring clarity among developers as to how to access/modify the property and methods, to decide whether to extend the class or not.
The properties that are set inside its respective class is validated and set to correct values and it is safe to be used inside the Class without checking the property type.
It is not a foolproof way to secure the data from modification.
The Purpose of Closures is to throw a piece of function into a variable or another function to perform some activity once in a while. Instead of dedicating a separate section code in global scope for performing an action once in a while and not look at it later you can use closures.
Reflections are meant to introspect objects to know its properties, methods, class etc. It is useful to identify dependencies.
Larvel uses reflection to perform dependency injection of objects.
Yes as you said you can use Closures and Reflection to work around visibility but it should be viewed as a language feature rather than a design flaw as no language can secure data 100%

Are there advantages to using __get/__set instead of traditional getter/setter methods except for less code?

coming from Java, I only have a few vacational visits to PHP. Looking at magic get and set methods, my (Java influenced) tummy starts hurting: It looks as if you were accessing properties directly (although, of course, you are actually are using __get and __set).
So - except for less code you have to write, are there any advantages to using magic getter and setter methods instead of traditional getX()/setX() methods? Should I start using them when coding PHP?
Thanks and best!
The only benefit of __get() is the possibility of less code, but even then it's not necessarily the case. For example, if you have a set of 10 private members and you want the getter to reveal 5, you have to write __get() so that if one of the psuedo-visible members is called, you send it. Otherwise, you either issue an error (that would otherwise come naturally without __get() or return a value such as null that may not actually be helpful.
I must excoriate anyone who suggests using getters and setters in general at all. This usually indicates a problem with architecture. Explain the conceptual difference between the two following code blocks, for instance:
class _ {
public $_;
}
vs.
class _ {
private $_;
public function get_() {
return $this->_;
}
}
There isn't a difference.
However, as many will point out the advantage of having a getter is that this allows you to modify the return value in some way transparently to make it useful for the recipient. However, we come back to architecture problems. You should never have to expose the contents of a class for any reason at all. Instead, you should tell the class to perform an action (which may vary based on its state). Using getters generally lends to querying the class' state and performing an action externally based on the viewed state.
I have essentially the same arguments against __set() and setters, but there is one nice thing that __set() lets you do:
class _ {
private $_ = array();
public function __set($key, $val) {
$this->_[$key] = $val;
}
}
This lets you type the very nice $_obj->key = 'val'. Note that there is not much difference from this and adding another method such as add() that takes the key and value and does the same thing, I just prefer the object setter notation.
__get__ and __set__ are fully dynamic. So for example you can start a database request if they are called to enable lazy loading. Of course, you could do this with getters and setters, too, but then you would have to do this every time. You can also do something like AOP because every property call gets passed through one single method. So all in all __get__/__set__ offer more flexilibility against time they take to process. You can do really advanced/cool stuff with it.
The advantages are that when you're refactoring, direct assignments / reads can be handled without the need to immediately change the complete codebase too, the code can be somewhat shorter, and people can create strings somewhat more easily (for example: $title="<title>{$obj->title}</title>"; vs. $title='<title>'.$obj->getTitle().'</title>';.
However, __get & __set methods can become large and unwieldy fairly quickly, and when coding properly & explicitly, it is in my opinion better to use explicit set/getX() methods to make clear functions are called, and the minor increase of code verbosity is as far as I'm concerned justified as one can easily see what actually calls a function and what doesn't. A possible exception could be when you are building a decorator for another class/object, but that's about it.
there is few difference between getter and setter methods and __set() and __get() methods! these are magic methods!
__set() use when you wanna assign undefined state to a object and so __get() also use to fetch value of undefined state!
setter and getter are used to assign or fetch value of defined states
except for less code you have to write, are there any advantages to using magic getter and setter >methods instead of traditional getX()/setX() methods? Should I start using them when coding PHP?
Given that less code to write it's already a strong reason to start use them.
the other reason is that you can add a common behaviour to all your getter/setter
function __set() {
//> Do some code in common between all setter
//> set your var here
}
When writing getX()/setX() for each attribute, practically speaking, you'll have at a minimum, 7 lines of code. This is assuming that your opening method brace is on the same line as the definition and you only put a single line of code into the method, then you have your closing brace on its own line.
For a non-trivial object, multiply that by 6 (YMMV). That is 42 lines just for attribute access/mutation. That does not include input validation or normalization. For an alternative, check out: https://github.com/metaphp/attributes
There are overheads in dynamic programming (e.g. using magic methods). An old benchmark: Benchmarking magic
As PHP is a dynamic (and not a completely enterprise) language, reducing code lines and missing some nanoseconds seems good idea in many cases (for debugging, scalability, reducing errors and etc).

Independent getter/setter methods, or combined?

While working on a project, I've been making some changes and browsing around existing framework API docs for insight.
While perusing the Kohana docs, I noticed that the getters/setters of any given class are typically combined:
public function someProperty($value = null){
if(is_null($value){
return $this->_someProperty;
}
$this->_someProperty = $value;
return $this;
}
Rather than:
public function setSomeProperty($value){
$this->_someProperty = $value;
return $this;
}
public function getSomeProperty(){
return $this->_someProperty;
}
Is there any value in doing this (the former), beyond lessening the method count of a given class? I was always under the understanding that methods (functions in general) should be more descriptive of an action. Do other experienced developers cringe, even a tiny bit, when they see this?
I was just surprised to see a popular framework use such conventions (I haven't used Kohana of course)
I consider this bad practise because it violates CommandQuerySeparation. Setting a value is changing state (Command). Getting a value is asking for state (Query). A method should not do both, but one thing only.
Also, it's not really obvious what a method does when it's just called username, e.g. does not have a verb, like get or set. This gets even worse in your example, because the return value is either the object itself or the property value, so its not consistent.
Moreover, getters (and setters) should be used sparingly as they will quickly convolute your API. The more getters and setters you have, the more knowledge about an object is required by collaborators of that object. If you find your objects asking other objects about their internals, chances are you misplaced the responsibilities.
jQuery goes the same way as Kohana. However I think it's better to create separate methods for setting and getting. It's more obvious what the method does and I think it's more practically in code-completition in your ide. For example you type set and you get a list of all Properties you can set.
Another disadvantage is: what if you want to set a value really to null? This wouldn't work since the null is the identifier for returnin the value, you are restricted in setting specific values...
So it's nice, since you'll have to write less, but hey what are three letters (set/get) in front of your methods?
Despite the fact that Kohana uses such unusual technique for the OOP, I think you should follow coding conventions at first. But of course it's better to use separate getters and setters for every property in your classes. So, if it's possible to use them not breaking the conventions - just do it and you won't be wrong ;) . You can also read here about good habits in PHP OOP - http://www.ibm.com/developerworks/opensource/library/os-php-7oohabits/ if you've doubted about using some OOP technics. Hope that it'll help :)
I'd rather believe they had a reasonable explanation for doing it this way. For example, for easier implementation of ArrayAccess. Only way to know for sure is to ask them directly.
To answer your question, yes I cringe when I see the first method. Goes against OOP principles.
Why not do it like this?
public function someProperty($value = null)
{
if (func_num_args() === 1) {
$this->someProperty = $value;
return $this;
} else {
return $this->someProperty;
}
}
This would imo be the only correct way to implement a combined getter/setter
If you do it everywhere it is a good way, but than it really needs to be for everything, maybe the programmers of this framework are used to is, (it's a bit jquery alike)
However it would confuse me
For setting and getting I always use setters and getters:
public function __set($key, $value) {
// assign value $value to $this->key
}
public function __get($key) {
// return value of this->key
}
For the sake of argument,
The combined approach does offer some benefits:
Avoids __get and __set magic while still emulating a public property. (I would not ever recommend using magic for these situations anyway)
Using thing() is less verbose than using getThing() setThing().
Even though the methods will be doing more, they can still be considered as "doing one thing()", that is handling the thing(). Properties also do more than one thing. They allow you to set and get values.
It's argued that the thing() doesn't give a verb. However, we can assume that a thing() without a verb means that we use it like a property (we get and set it). For interfaces, we can say that a thing() with no argument is readonly and a thing($arg) with an argument is read/write. Why should we be shy from adopting this? At some point we adopted the idea of adding getters and setters didn't we?
If you are using a web-based language (like PHP), then chances are you might be using jQuery as well. JQuery is already doing this sort of thing() and it has worked out well.
Using func_num_args(), as mentioned already, helps achieve this approach perfectly.
Personally, I've already taken a good portion of risks in my current apps at this point so I'm probably going with the old tried-and-true getters and setters (see the section "Finding the Balance" of Jimmy Bogard's post in regards to getters/setters for data operations). And I suppose we are already trained to look for these get/set prefixes (as well as our IDE's) to see what properties we can work with in a class. This is a discussion I would be open to returning to at some point.

what are the tradeoffs of using accessor methods vs public variables in php

I'm looking for advice/experience on using public variables vs private variables with accessor methods in php.
eg
$obj->foo = 'a';
echo $obj->foo;
vs
$obj->setFoo('a');
echo $obj->getFoo();
What I like about public variables is the shorter syntax - just seems less work to use. I understand that it could make refactoring more difficult later, but I've never experienced it (meaning, sometimes the design changes - but usually the accessor methods would need to be changed any.)
The other option is to store the variables in an array and use magic methods (__get/__set) to access them - then I have the ease of use of public variables with the ability to refactor or accessor methods.
Any experience or references of what people do in the php world.
And for anyone that hold the accessor method are the best way, is there a valid need/use for public variables?
Yes, accessor methods are an overhead, although the syntax for using setters/getters is just as clean as direct access of public properties... slightly more wordy, but just as clean.
Biggest benefit of accessor methods is that you can use your set method to validate values and reject inappropriate values (e.g. trying to set a property that should always be an integer to a string or an array)... but this verification only works if external code can't access the property directly.
Second benefit if your code has related properties, where a change to property A requires a change to property B as well... if the properties are public, you can't control (or enforce) this.
Using set methods allows you to implement fluent interface, or to cleaner code for instances like:
echo $obj->setFoo('a');
instead of
$obj->setFoo('a'); echo $obj->getFoo();
if you include a return in your set method
setters and getters are always the best option because they provide more stability for validation / sanitization.
public function __call($name,$params = array())
{
if(strstr('set',$name))
{
}//returns
if(strstr('get',$name))
{
}//Returns
if(strstr('run',$name))
{
}//Returns
}
Getters/Setters arose in Java. They have no place in scripting languages, hence they are frowned upon in e.g. Python and Javascript. They make the API more combersome.
As you already know, you can use __get to wrap variable access. This is advisable in scripting languages. It allows you to e.g. validate types in a central location, you don't have duplicated code in multiple setters/getters.
function __set($name, $value) {
if (gettype($value) == $this->_types[$name]) {
$this->_vars[$name] = $value;
}
} // instead of twenty methods checking the type
It's a code smell to implement hollow getters/setters to have enterprisey-looking code. And it's also inadvisable to have getters/setters with side-effects. Always use real methods / messages for complex object operations.
Setters and Getters are one kind of implementation for encapsulation, one of the OOP principles, which says an object must be a black box just exposing behaviors and its state to its clients, but preventing the exposure of its internal. This allows low coupling code as you can change the logic inside a Setter and / or Getter without affecting the client code using your API.
As many other have stated before, there are other implementations such as magic methods.

Is it really that wrong not using setters and getters?

I'm kind of new in PHP. For some reason in other types of programming languages like JAVA I have no problem with using setters and getters for every single variable, but when I'm programming in PHP probably because it is so flexible it feels kind of like a waste of time. It feels simpler to just set the class attributes as public most of the time and manipulating them like that. The thing is that when I do it like this I feel like I'm doing something wrong and going against OO principles.
Is it really that wrong not using setters and getters? Why or why not? How do you guys do it most of the time?
The main problem with not using property accessors is that if you find out you ever need to change a field to a property later on – to make it a computed property in a subclass, for instance – you’ll break clients of your API. For a published library, this would be unacceptable; for an internal one, just quite a lot of work fixing things.
For private code or small apps, it could be feasible to just wing it. An IDE (or text editor) will let you generate accessor boilerplate and hide it using code folding. This arguably makes using getters and setters mechanically fairly easy.
Note that some programming languages have features to synthesise the default field+getter+setter – Ruby does it via metaprogramming, C# has auto-implemented properties. And Python sidesteps the issue completely by letting you override attribute access, letting you encapsulate the attribute in the subclass that needs it instead of having to bother with it up front. (This is the approach I like best.)
The point of getters or setters is that you can still add logic to your modifications of the field in one place instead of everyplace you want to modify or retrieve the field. You also gain control at class level what happens with the field.
If we're talking strictly about PHP here and not about C#, Java, etc (where the compiler will optimise these things), I find getters and setters to be a waste of resources where you simply need to proxy the value of a private field and do nothing else.
On my setup, I made two crappy classes, one with five private fields encapsulated by five getter/setter pairs proxying the field (which looked almost exactly like java code, funnily enough) and another with five public fields, and called memory_get_usage() at the end after creating an instance. The script with the getter/setters used 59708 bytes of memory and the script with the public fields used 49244 bytes.
In the context of a class library of any significant size, such as a web site framework, these useless getters and setters can add up to a HUGE black hole for memory. I have been developing a framework for my employer in PHP (their choice, not mine. i wouldn't use it for this if i had the choice but having said that, PHP is not imposing any insurmountable restrictions on us) and when I refactored the class library to use public fields instead of getters/setters, the whole shebang ended up using 25% less memory per request at least.
The __get(), __set() and __call() 'magic' methods really shine for handling interface changes. When you need to migrate a field to a getter/setter (or a getter/setter to a field) they can make the process transparent to any dependent code. With an interpreted language it's a bit harder to find all usages of a field or method even with the reasonably good support for code sensitivity provided by Eclipse PDT or Netbeans, so the magic methods are useful for ensuring that the old interface still delegates to the new functionality.
Say we have an object which was developed using fields instead of getters/setters, and we want to rename a field called 'field' to 'fieldWithBetterName', because 'field' was inappropriate, or no longer described the use accurately, or was just plain wrong. And say we wanted to change a field called 'field2' to lazy load its value from the database because it isn't known initially using a getter...
class Test extends Object {
public $field;
public $field2;
}
becomes
class Test extends Object {
public $fieldWithBetterName = "LA DI DA";
private $_field2;
public function getField2() {
if ($this->_field2 == null) {
$this->_field2 = CrapDbLayer::getSomething($this->fieldWithBetterName);
}
return $this->_field2;
}
public function __get($name) {
if ($name == 'field')) {
Logger::log("use of deprecated property... blah blah blah\n".DebugUtils::printBacktrace());
return $this->fieldWithBetterName;
}
elseif ($name == 'field2') {
Logger::log("use of deprecated property... blah blah blah\n".DebugUtils::printBacktrace());
return $this->getField2();
}
else return parent::__get($name);
}
}
$t = new Test;
echo $t->field;
echo $t->field2;
(As a side note, that 'extends Object' bit is just a base class I use for practically everything which has a __get() and a __set() declaration which throws an exception when undeclared fields are accessed)
You can go backwards with __call(). This example is quite brittle, but it's not hard to clean up:
class Test extends Object {
public $field2;
public function __call($name, $args) {
if (strpos($name, 'get')===0) {
$field = lcfirst($name); // cheating, i know. php 5.3 or greater. not hard to do without it though.
return $this->$field;
}
parent::__call($name, $args);
}
}
Getter and setter methods in PHP are good if the setter has to do something, or if the getter has to lazy load something, or ensure something has been created, or whatever, but they're unnecessary and wasteful if they do nothing other than proxy the field, especially with a few techniques like the ones above to manage interface changes.
I am probably not going to get many upvotes on this one, but personally getters and even more so setters feel like a code smell to me. Designs should be behavior driven, not data driven. Of course, this is just an opinion. If you have an object that depends on a particular data field of another object this is very tight coupling. Instead it should depend on the behavior of that object which is far less brittle than its data.
But yes, property like getters and setters are a step up from a dependency on a field directly for this very reason. It is less brittle and loosens up the coupling between the objects.
Did you consider to use magic functions __set/__get? Using them you can easily merge all getter/setter function in only 2 functions!
There is a way to emulate get/set without actually using get/set function class, so your code remains tidy:
$person->name = 'bob';
echo $person->name;
Take a look at this class I have coded.
Typically, when using this class, you would declare all your properties protected (or private). In the event where you'd want to add a behaviour on a property, say strtolower() + ucfirst() on the "name" property, all you'd need to do is declare a protected set_name() function in your class and the behavior should get picked up automatically. Same can be accomplished with get_name().
// Somewhere in your class (that extends my class).
protected function set_name($value) { $this->name = ucfirst(strtolower($value)); }
//
// Now it would store ucfirst(strtolower('bob')) automatically.
$person->name = 'bob';
P.S.
Another cool thing is you can make up non-existing fields such as
echo $person->full_name;
without having such fields (as long as there is a get_full_name() function).
If you access these variable in your script lots of time and if you update yoru class often you should use setters and getter because but if you dont this , when you improve your class you have to update all files which uses this variable .
Secondly main reason why you do this is you should not access variable directly because class structure may change and this data can be providen differently.While you are getting data from class you should not care about how this data is generated .Class have to care about this data proccessing so you only should care what will you get.

Categories