我是一个PHP菜鸟,当我阅读一些joomla模块的PHP文件并尝试学习时,我遇到了这个:
class RokSprocket_Item
{
protected $text;
public function setText($introtext)
{
$this->text = $introtext;
}
public function getText()
{
return $this->text;
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,因为函数getText()只是返回$this->text而没有其他任何东西,为什么要使用它?在我看来$this->getText()可以完全取代$this->text.
$something = $object->property通过将属性设置为公共,那么您也允许$object->property = $something.这将绕过您可能在其中运行的任何类型的验证[或其他] $object->setProperty().如果您没有看到任何理由将您的类属性设置为私有或受保护或创建getter和setter,那就是您的调用.然而,有很多理由说明为什么它们是好主意.
编辑:这是我一直在使用的一些代码的快速示例:
<?php
Class Registry {
private $vars = array();
public function __set($index, $value) {
$this->vars[$index] = $value;
}
public function __isset($index) {
return isset($this->vars[$index]);
}
public function __get($index) {
if( isset($this->vars[$index]) ) {
return $this->vars[$index];
} else {
throw new Exception("Index $index not set.");
}
}
}//-- end class Registry --
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
230 次 |
| 最近记录: |