Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessor and mutator?

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

like image 425
never_had_a_name Avatar asked May 04 '10 06:05

never_had_a_name


People also ask

What is the difference between an accessor and a mutator?

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.

What is an accessor and mutator method?

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 are accessors?

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.

What is an accessor in Java?

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.


1 Answers

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.

like image 111
Relaxing In Cyprus Avatar answered Sep 18 '22 15:09

Relaxing In Cyprus