Lit*_*ito 6 php extends class object
我有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);
?>
Run Code Online (Sandbox Code Playgroud)
我能做谁?
无效例如:
<?php
class Extended extends Main {
function __construct ($main) {
foreach ($main as $k => $v) {
$this->$k = $v;
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我需要一些更透明,更有效的解决方案:)
小智 6
使用简单的构造函数很容易实现
<?php
class One {
public static $string = "HELLO";
}
class Two extends One {
function __construct()
{
parent::$string = "WORLD";
$this->string = parent::$string;
}
}
$class = new Two;
echo $class->string; // WORLD
?>
Run Code Online (Sandbox Code Playgroud)
编辑:这可以通过控制反转(IoC)和依赖注入(DI)更好地解决。如果您使用自己的框架或没有依赖注入容器的框架,请尝试League/Container
下面的答案作为愚蠢答案的历史。
我认为正确的方法。
<?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";
Run Code Online (Sandbox Code Playgroud)