Getter and Setter?
I'm not a PHP developer, so I'm wondering if in PHP is more popular to use explicit getter/setters, in a pure OOP style, with private fields (the way I like):
class MyClass {
private $firstField;
private $secondField;
public function getFirstField() {
return $this->firstField;
}
public function setFirstField($x) {
$this->firstField = $x;
}
public function getSecondField() {
return $this->secondField;
}
public function setSecondField($x) {
$this->secondField = $x;
}
}
or just public fields:
class MyClass {
public $firstField;
public $secondField;
}
Thanks
Solution 1:
You can use php magic methods __get
and __set
.
<?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
Solution 2:
Why use getters and setters?
- Scalability: It's easier refactor a getter than search all the var assignments in a project code.
- Debugging: You can put breakpoints at setters and getters.
- Cleaner: Magic functions are not good solution for writting less, your IDE will not suggest the code. Better use templates for fast-writting getters.
Solution 3:
Google already published a guide on optimization of PHP and the conclusion was:
No getter and setter Optimizing PHP
And no, you must not use magic methods. For PHP, Magic Method are evil. Why?
- They are hard to debug.
- There is a negative performance impact.
- They require writing more code.
PHP is not Java, C++, or C#. PHP is different and plays with different roles.
Solution 4:
Encapsulation is important in any OO language, popularity has nothing to do with it. In dynamically typed languages, like PHP, it is especially useful because there is little ways to ensure a property is of a specific type without using setters.
In PHP, this works:
class Foo {
public $bar; // should be an integer
}
$foo = new Foo;
$foo->bar = "string";
In Java, it doesn't:
class Foo {
public int bar;
}
Foo myFoo = new Foo();
myFoo.bar = "string"; // error
Using magic methods (__get
and __set
) also works, but only when accessing a property that has lower visibility than the current scope can access. It can easily give you headaches when trying to debug, if it is not used properly.