我们知道,在php中使用require_once/include_once虽然方便,但是代价昂贵,据测试数据来看,require_once比require慢3-4倍,所以在php开发中,我们应该尽量使用require/include。 列一下俺常用的避免require/include的方法。 使用__autoload php5可以使用__autoload来避免require,用的好的话,代码里头甚至看不到几个require,实在是安逸啊。测试结果表明,使用__autoload之后的new Foo; 比require_once ‘foo.php’; new Foo; 大概要快3倍左右。 补充:为了避免autoload冲突,可以考虑使用spl_autoload_register(PHP 5 >= 5.1.2)来改变魔术函数__autoload的行为。 使用defined检测是否载入过 在代码开头使用defined检测是否定义过对应的常量,如果有的话,直接return。 <?php if(!defined('_MYCLASS_')) return; define('_MYCLASS_', 1); class MyClass { ... } ?> 测试了一下,defined的性能也不是太好… require前检查 用class_exists或者function_exists检查一下,确认没有载入过再出手,至少比require_once能快上3倍。php4也可以用上。 class_exists('myClass') or require('/path/to/myClass.class.php'); (责任编辑:admin) |