封装变量
重构动机
如果想要移走一处被广泛使用的数据,最好是先以函数形式封装所有对该数据的访问。
重构前
<?php
namespace app\controller;
class Index
{
public $bookName = '重构 改善既有代码的设计';
/**
* 更改书籍名称
*/
public function modifyBookName()
{
return $this->bookName = '重构(第二版)';
}
}
重构后
<?php
namespace app\controller;
class Index
{
protected $bookName = '重构 改善既有代码的设计';
/**
* @return string
*/
public function getBookName(): string
{
return $this->bookName;
}
/**
* @param string $bookName
*/
public function setBookName(string $bookName): void
{
$this->bookName = $bookName;
}
/**
* 更改书籍名称
*/
public function modifyBookName()
{
$this->setBookName('重构(第二版)');
return $this->getBookName();
}
}