[英]Organize and relate class in 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. 我想要的是在Main
类中拥有所有内容,创建$Main
对象,然后从那里访问任何其他对象。 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
. Db
将需要Config
一个常量,但是我不想在Db
创建新的Config
,而是使用Main
的一个。 The same happens with Info. 信息也会发生同样的情况。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.