我正试图充分利用面向对象的PHP并学习一些东西。 继MVC的教程中,我能做到这一点:如何创建一个包含几个可以相互通信的类的类?
class Repository {
private $vars = array();
public function __set($index, $value){
$this->vars[$index] = $value;
}
public function __get($index){
return $this->vars[$index];
}
}
/*
*/
function __autoload($class_name) {
$filename = strtolower($class_name) . '.class.php';
$path = dirname(__FILE__);
$file = $path.'/classes/' . $filename;
if (file_exists($file) == false){
return false;
}
include ($file);
}
//Main class intialization
$repo = new Repository;
//Configuration loading
$repo->config = $config;
//Classes loading
$repo->common = new Common($repo);
$repo->db = new Database($repo);
$repo->main = new Main($repo);
然后每一类将遵循此模板:
class Database{
private $repo;
function __construct($repo) {
$this->repo= $repo;
}
}
这样我可以访问所加载的类的所有方法和VAR在一个前我在例子中,我能做到这一点之前,在主类:
$this->repo->db->someMethod();
令我惊讶的是,对象$回购获取每个时间的复制ew类被加载是一个问题记忆明智吗?有没有更好的方法来做到这一点?这是可以在真实项目中使用的东西吗?
非常感谢您
相关并且可能良好的阅读:http://stackoverflow.com/questions/1812472/in-a-php-project-how-do-you-organize-and-access-your-helper-对象 – 2010-08-16 10:10:02
@Pekka非常感谢您的精彩阅读! – 0plus1 2010-08-16 10:20:12