when using doctrine i stumble upon these 2 words: accessor and mutator.
are these only used in doctrine or are they specific for php?
and what do they mean?
thanks
An accessor is a class method used to read data members, while a mutator is a class method used to change data members. It's best practice to make data members private (as in the example above) and only access them via accessors and mutators.
Introduction. In Java accessors are used to get the value of a private field and mutators are used to set the value of a private field. Accessors are also known as getters and mutators are also known as setters.
What Does Accessor Mean? In computer programming, an accessor method is a method that fetches private data that is stored within an object. An accessor provides the means by which to obtain the state of an object from other program parts.
In Java, accessor methods return the value of a private variable. This gives other classes access to that value stored in that variable. without having direct access to the variable itself. Accessor methods take no parameters and have a return type that matches the type of the variable they are accessing.
They aren't just different terms for getters and setters, at least not in Laravel.
To quote the documentation: "Accessors and mutators allow you to format Eloquent attributes when retrieving them from a model or setting their value."
https://laravel.com/docs/master/eloquent-mutators
So, you could say that getters and setters are a subset of accessors and mutators which change the data by a factor of zero.
Put it another way, if I wanted to get a raw field "cost" from a table, I would use a getter. If I wanted to get that field expressed and formatted in pounds and pence, then I could use an accessor.
There are other ways I could go about it, but that's one option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With