PHP, MySQL, & JavaScript All-in-One For Dummies
Book image
Explore Book Buy On Amazon
Mutator magic methods are PHP methods that change the value of a property that you set with the private visibility. These are also commonly called setters.

The preferred way to handle class properties is to make them private so external programs can’t change them directly. Instead, to manipulate the data, external programs are forced to use mutator magic class methods that interface with the properties.

The mutator magic method in PHP is __set() (note the leading double underscores). You use the mutator magic method to set all the values of the properties in the class with a single method definition:

public function __set($name, $value) {
    $this->$name = $value;
}
The mutator uses two parameters: the name of the property to set and the value to assign to the property. Where the magic comes into play is with how PHP uses the mutator. In your PHP application code, you don’t actually have to call the __set() mutator method. You can define the $description property just by using a simple assignment statement:

PHP automatically knows to look for the __set() mutator method defined for the class and runs it, passing the appropriate property name and value. Even though the $description property is set to the private visibility, by defining the mutator magic method you can allow external programs to assign a value to the property. The benefit of using mutators, though, is that you can control how external programs use the properties you define for the class. With the mutator definition, you can place any code you need to control property features, such as ranges of values allowed or the allowed settings applied to the property. For example, you could so something like this:

public function __set($name,$value) {
    if ($name == "price" && $value < 0) { $this->price = 0;
    } else {
        $this->$name = $value;
    }
}
This example checks if the property being set is the $price property. If it is, it checks if the value is less than 0. If the value is less than 0, the price is set to 0 instead of the supplied price value. This gives you a way to control the value that is set for the price from external programs that use the class object.

About This Article

This article is from the book:

About the book author:

Richard Blum has more than 30 years of experience as a systems administrator and programmer. He teaches online courses in PHP, JavaScript, HTML5, and CSS3 programming, and authored the latest edition of Linux For Dummies.

This article can be found in the category: