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.