What are Accessor Magic Methods in PHP?

Accessor magic methods are PHP methods you use to access the private property values you define in the class. Creating special methods to retrieve the current property values helps create a standard for how other programs use your class objects. These methods are often called getters because they retrieve (get) the value of the property.

You define the accessor using the special __get() method:

public function __get($name) {
return $this->$name;
}

That’s all there is to it! Accessor methods aren’t overly complicated; they just return the current value of the property. To use them you just reference the property name as normal:

echo "&lt;p&gt;Product: $prod1-&gt;description&lt;/p&gt;\n";

PHP automatically looks for the accessor method to retrieve the property value. Follow these steps to try creating and using a class definition with mutators and accessors:

Save the file as ooptest2.php in the DocumentRoot folder for your web server.

Ensure that the web server is running, and then go here to test your code.

Close the browser window when you’re done.

The image below shows the output that you should see when you run the program in your browser.

The output from the ooptest2.php program.

There’s a lot going on in this example, so hang in there with me! First, the PHP code defines the Product class, using the four properties, but this time it defines them with private visibility. Following that, the mutator and accessor magic methods are defined. The mutator checks to ensure the price and inventory properties can’t be set to a negative value.

After the class definition, the code creates an instance of the Product class, and experiments with the inventory values. First, it uses the buyProduct() method to purchase four carrots. That works just fine.

Next, it uses the mutator to set the inventory property for the carrot object to a negative value. The mutator code intercepts that request and prevents the inventory from being set, instead producing an error message.

Finally, the code tries to use the buyProduct() method to purchase more carrots than what’s set in inventory. The added code in the buyProduct() method prevents that from happening.

Now the class definition is starting to do some useful functions for the application. But wait, there are more magic methods available for you to use!