Setters/Getters, Visibility [ OOP ] in PHP

I'm in the process of reformatting my class ( seen below ) - I think I made the mistake of setting everything with the same visibility in my class, whereas properties should really be private and getters/setters should be public in most cases.

To grab a property I just do $path->propertyname but I've noticed its more practical to have setters/getters. If I were to implement getters, should I make one for each property or can I make one for the entire class? So for example say I want to get the controller name...

public function getController( ) {
    return $this->controller;
}

And that would return the controller private property? Is it common to have a more generic getter/setter or even a hybrid method that gets and sets for me?

Here's the class structure ( just properties/methods ):

class urlParser {

    public static $url      = '';
    public static $controller   = '';
    public static $baseController = '';
    public static $urls     = '';
    public static $template     = '';
    public static $captures     = '';
    public static $contentXML   = '';

    function __construct( $urls ) {

        $this->urls = $urls;

        $this->baseController = $urls['default'];

        $this->get_url();
    }

    public function get_url() {
        // sets following properties:
        // url, template, controller, contentXML, baseController
    }
}

Having setters and getters in you case is pointless.

In case you have to do anything besides returning controller, you don't need getter as you don't need setter if you don't do anything with property after it has been set.

In case you really want getters and setters, you can use __get and __set magic methods for all your properties. But that is totally pointless if the case is as I described above.


take a look at overloading in php: http://php.net/overload

there are two magic methods __get() and __set() which might do exactly what you want


PHP objects have some nice magic methods (although I don't use all of them because it can get confusing). The one you may be looking for is __get() and __set(). You would still have to refactor all of your code if you choose to make your data fields private (which you should so that you don't have your other code accessing fields incorrectly. Doing it this way helps make your code a little better and easier to maintain.

Although, I usually try to have getters and setters for each private data field because you can easily see any validation for each field. Plus I'm more of a Java developer than a PHP developer.

链接地址: http://www.djcxy.com/p/53946.html

上一篇: C#速记getter和setter

下一篇: Setters / Getters,可见性[OOP] in PHP