代码之家  ›  专栏  ›  技术社区  ›  0plus1

如何创建一个包含几个可以相互通信的类的类?

  •  1
  • 0plus1  · 技术社区  · 15 年前

    我正试图充分利用面向对象的php,并在此过程中学习一些东西。

    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;
        }
    }
    

    这样我就可以访问在我所在的类之前加载的类的所有方法和变量。在主类中执行此操作之前的示例中:

    $this->repo->db->someMethod();
    

    1 回复  |  直到 15 年前
        1
  •  3
  •   Nicolas78    15 年前

    我没有 相当地 确定你想要达到的目标(我想关于如何做这件事有一些新的想法;),但是你可以放松一下对记忆的消耗;您只传递对同一个对象的引用,所以复制的只是指向对象实例的4字节指针!

    网卡

    推荐文章