我不是PHP开发人员,所以我想知道在PHP中使用显式getter/setter的优点和缺点是什么,在纯OOP风格中,带有私有字段(我喜欢的方式):
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;
}
}
或者只是公共字段:
class MyClass {
public $firstField;
public $secondField;
}
如果你喜欢使用__call函数,你可以使用这个方法。它适用于
GET => $this->属性()
SET => $this->属性($value)
getProperty() => $this->
SET => $this->setProperty($value)
kalsdas
public function __call($name, $arguments) {
//Getting and setting with $this->property($optional);
if (property_exists(get_class($this), $name)) {
//Always set the value if a parameter is passed
if (count($arguments) == 1) {
/* set */
$this->$name = $arguments[0];
} else if (count($arguments) > 1) {
throw new \Exception("Setter for $name only accepts one parameter.");
}
//Always return the value (Even on the set)
return $this->$name;
}
//If it doesn't chech if its a normal old type setter ot getter
//Getting and setting with $this->getProperty($optional);
//Getting and setting with $this->setProperty($optional);
$prefix = substr($name, 0, 3);
$property = strtolower($name[3]) . substr($name, 4);
switch ($prefix) {
case 'get':
return $this->$property;
break;
case 'set':
//Always set the value if a parameter is passed
if (count($arguments) != 1) {
throw new \Exception("Setter for $name requires exactly one parameter.");
}
$this->$property = $arguments[0];
//Always return the value (Even on the set)
return $this->$name;
default:
throw new \Exception("Property $name doesn't exist.");
break;
}
}
除了这里已经很好的和受人尊敬的答案之外,我还想扩展一下没有setter /getter的PHP。
PHP没有getter和setter语法。正如Dave所指出的那样,它提供了子类或魔法方法来允许“挂钩”和覆盖属性查找过程。
魔术让我们这些懒惰的程序员在积极参与一个项目并熟悉它的时候,用更少的代码做更多的事情,但通常是以可读性为代价的。
在PHP中,由于强制使用类似getter/setter的代码架构而导致的每个不必要的函数,都会在调用时涉及自己的内存堆栈框架,并浪费CPU周期。
可读性:代码库会导致代码行膨胀,这会影响代码导航,因为更多的LOC意味着更多的滚动。
偏好:个人而言,作为我的经验法则,我接受静态代码分析的失败
作为避免走上这条神奇之路的标志,只要我当时没有明显的长期利益。
谬论:
一个常见的论点是可读性。例如,$someobject->width比$someobject->width()更容易读取。然而,与行星的周长或宽度可以假定为静态的不同,对象的实例(例如$someobject)需要一个width函数,可能需要测量对象的实例宽度。
因此,可读性的提高主要是因为确定的命名方案,而不是通过隐藏输出给定属性值的函数。
__get / __set使用:
属性值的预验证和预清理
字符串。
"
一些{mathsobj1->generatelatex}多
行文本{mathsobj1->latexoutput}
{mathsobj1->generatelatex}有很多变量
一些原因
"
在这种情况下,generatelatex将遵循actionname + methodname的命名方案
特殊的,明显的案例
dnastringobj - >同源框(one_rememberable_parameter美元)- >千钧一发——> findrelated ()
dnastringobj - >同源框(one_rememberable_parameter美元)- > gttccaatttga - > findrelated ()
注意:PHP选择不实现getter/setter语法。我并不是说getter /setter一般都不好。