1,PHP5.3中引入了一个名为"延期静态绑定(late static binding)"的概念,这个概念和多态结合起来的一个有趣的例子如下
代码
abstract
class
BaseObject
{
public static function getInstance()
{
return new static ();
}
}
class User extends BaseObject
{
}
class Document extends BaseObject
{
}
print_r (Document :: getInstance());
{
public static function getInstance()
{
return new static ();
}
}
class User extends BaseObject
{
}
class Document extends BaseObject
{
}
print_r (Document :: getInstance());
static关键字这会在运行时动态绑定到Document类上去,因此getInstance方法会返回一个Document对象。
代码
abstract
class
BaseObject
{
private $group ;
public function __construct()
{
$this -> group = static :: getGroup();
}
public static function getGroup()
{
return " default " ;
}
public static function getInstance()
{
return new static ();
}
}
class User extends BaseObject
{
}
class Document extends BaseObject
{
public static function getGroup()
{
return " document " ;
}
}
print_r (User :: getInstance());
print_r (Document :: getInstance());
{
private $group ;
public function __construct()
{
$this -> group = static :: getGroup();
}
public static function getGroup()
{
return " default " ;
}
public static function getInstance()
{
return new static ();
}
}
class User extends BaseObject
{
}
class Document extends BaseObject
{
public static function getGroup()
{
return " document " ;
}
}
print_r (User :: getInstance());
print_r (Document :: getInstance());
可以看到BaseObject的构造函数中调用了静态方法getGroup,在运行时会根据调用类的实际情况调用不同的getGroup方法。
2,“以空间换时间”,项目中应该考虑合理利用缓存来避免重复进行的查询等工作,最近一次代码优化过程中,加入缓存后的程序效率提高了5倍。部分代码如下:
代码
def
getFileds(self):
#
查询表的所有列名
global FieldsDict
if self._table in FieldsDict.keys(): # 全局缓存中有,则直接使用
self._fields = FieldsDict[self._table]
else :
sql = " select distinct column_name from information_schema.columns where table_name = '%s' and TABLE_SCHEMA='%s' order by ordinal_position " % (self._table, Base._dbHelper.getDataBaseName())
fields = self.fetch_rows(sql)
for field in fields:
self._fields.append(field[ ' column_name ' ])
FieldsDict[self._table] = self._fields # 保存到全局缓存中
global FieldsDict
if self._table in FieldsDict.keys(): # 全局缓存中有,则直接使用
self._fields = FieldsDict[self._table]
else :
sql = " select distinct column_name from information_schema.columns where table_name = '%s' and TABLE_SCHEMA='%s' order by ordinal_position " % (self._table, Base._dbHelper.getDataBaseName())
fields = self.fetch_rows(sql)
for field in fields:
self._fields.append(field[ ' column_name ' ])
FieldsDict[self._table] = self._fields # 保存到全局缓存中
另外,开发和生成环境之间的切换开关要做充分,便捷的开关控制可以保证代码的迅速上线。