Question

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

Was it helpful?

Solution

They're just fancy terms for getters and setters.

class MyClass
{
    private $prop;

    // Accessor (or Getter)
    public function getProp()
    {
        return $this->prop;
    }


    // Mutator (or Setter)
    public function setProp($value)
    {
        $this->prop = $value;
    }

}

OTHER TIPS

Shouldn't we be using __get and __set in php5 and later now?

If I understand you correctly these 2 are specific to I guess any object oriented programming language. The point is that accessor is a method or a function which provides access to private fields in your class and mutator method allows to modify the private fields. I can go on writing about this, but I suggest you just google these, and you'll get lots of information about it. Its all about encapsulation <- suggest you to look up that term as well.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top