我有2个课程,主要和扩展.我需要在扩展类中使用主变量.
<?PHP class Main { public $vars = array(); } $main = new Main; $main->vars['key'] = 'value'; class Extended extends Main { } $other = new Extended; var_dump($other->vars); ?>
我能做谁?
无效例如:
<?PHP class Extended extends Main { function __construct ($main) { foreach ($main as $k => $v) { $this->$k = $v; } } } ?>
我需要一些更透明,更有效的解决方案:)
编辑:使用控制反转(IoC)和依赖注入(DI)可以更好地解决这个问题.如果您使用自己的框架或没有依赖注入容器的框架,请尝试
League/Container
原文链接:https://www.f2er.com/php/131934.html下面的回答是愚蠢答案的历史.
我想的正确方法.
<?PHP class Config { protected $_vars = array(); protected static $_instance; private function __construct() {} public static function getInstance() { if (!isset(self::$_instance)) { self::$_instance = new self(); } return self::$_instance; } public function &__get($name) { return $this->_vars[$name]; } public function __set ($name,$value) { $this->_vars[$name] = $value; } } $config = Config::getInstance(); $config->db = array('localhost','root',''); $config->templates = array( 'main' => 'main','news' => 'news_list' ); class DB { public $db; public function __construct($db) { $this->db = $db; } public function connect() { MysqL_connect($this->db[0],$this->db[1],$this->db[2]); } } $config = Config::getInstance(); $db = new DB($config->db); $db->connect(); class Templates { public $templates; public function __construct($templates) { $this->templates = $templates; } public function load ($where) { return $this->templates[$where]; } } $config = Config::getInstance(); $templates = new Templates($config->templates); echo $templates->load('main') . "\n";