douqingzhi0980 2013-07-17 12:35
浏览 72
已采纳

用PHP组织和关联类

Well, I am trying to adapt my old code to a more object oriented model but I find difficulties in doing it. The structure of my classes would look like this:

// config.php
class Config {
    const Setting1 = 'value';
    const Setting2 = 'value';
}

// main.php
include 'config.php'

class Main {
    var $Config;
    var $Info;
    var $Db;

    function _construct() {
        $this->Config = &new Config;
        $this->Info = &new Info;
        $this->Db = &new Db($this);
    }
}

class Info {
    function getSetting($a, $Config) {
        if ($a>0) return $Config::Setting1;
        return $Config::Setting2;
    }
}

class Db {
    function _construct($Main) {
        $Setting1 = $Main->Config::Setting1;
    }
}

// index.php
$Main = new Main;
echo $Main->Info->getSetting(1, $Main->Config);

So, as you see, there are incorrect things in this code. What I want is to have everything inside the Main class, create the $Main object and from there access any other object. Db will need a constant from Config yet I don't want to create a new Config inside Db but use the one from Main. The same happens with Info.

  • 写回答

1条回答 默认 最新

  • douba1498 2013-07-27 17:56
    关注

    The problem should be fixed with this:

    // config.php
    class Config {
        public static $Setting1 = 'value';
        public static $Setting2 = 'value';
    }
    
    // main.php
    include('config.php');
    
    class Main {
        private $Info = null;
        private $Db = null;
    
        public function _construct() {
            $this->Info = new Info();
            $this->Db = new Db();
        }
    
        public function getSetting($a) {
            return $this->Info->getSetting($a);
        }
    }
    
    class Info {
        public function getSetting($a) {
            if ($a>0) return Config::$Setting1;
            return Config::$Setting2;
        }
    }
    
    class Db {
        public function _construct() {
            $Setting1 = Config::$Setting1;
        }
    }
    
    // index.php
    $Main = new Main();
    echo $Main->getSetting(1);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程