我的数据基础类 MyInfo
在面向对象的程序设计中,通常会在类中设计属性来储存数据,例如:
class foo
{
Private $name;
Public function setName($value) { $name = $value; }
Public function getName() { return $this->name; }
}
当一个类的属性很多时,这种 setName(), getName() 的工作量就会增加。
利用 __set(), __get() 的重载功能
在 PHP 中,对一个不存在的属性赋值时,将自动调用__set()方法,而调用一个不存在的属性时,将自动调用 __get() 方法。
利用这个特性,我设计一个数据的基础类,用一个 array 来管理所有不存在的属性,然后改写 __set() 及 __get()。
abstract class MyInfo
{
private $properties;
abstract public function isEmpty();
function __construct() {
$properties = array();
}
public function __destruct() {
if( $this->properties ) unset($this->properties);
}
public function __set($name, $value) {
$this->properties[$name] = $value;
}
public function __get($name) {
if( $this->IsKeyExists($name) )
return $this->properties[$name];
else {
return null;
}
}
// 检查此 $name 的资料是否存在?
public function IsKeyExists($name) {
if( !$this->properties ) return false;
return array_key_exists($name, $this->properties);
}
public function getProperties() {
return $this->properties;
}
}
最后这个getProperties() 方法,可以用来存取所有的属性名称及其值。当想要把所有属性值储存起来时,就会需要它。
有了这个基础类之后,我让所有的数据类都继承它。
class CategoryInfo extends MyInfo
{
function __construct() {
parent::__construct();
$this->ReSet();
}
public function reset() {
$this->AutoNo = 0;
$this->ParentNo = 0;
$this->ID = '';
$this->Title = '';
$this->SortKey = 0;
}
public function isEmpty() {
return ($this->AutoNo == 0);
}
}
在 reset() 中设定了所有的属性及其初始值。
结语
有了 MyInfo 后,我只要设定其初始值,也就等于设定了属性,减少了很多烦琐的工作,当然有些细节并未考虑的很清楚,像若属性名称打错字会如何等等,但小心使用为上,尽量避开这种问题。
参考资料
《PHP 从入门到精通》 陈超等编着 化学工业出版社