我正試圖充分利用面向對象的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