扩展类变量(PHP)
我试图用构造函数中的变量扩展一个类。这里有一个小例子 我的index.php中包含以下代码扩展类变量(PHP),php,Php,我试图用构造函数中的变量扩展一个类。这里有一个小例子 我的index.php中包含以下代码 <?php namespace System; require_once 'App/Config.php'; spl_autoload_register(function($class) use ($config) { require_once $config['app']['root'] . '/' . $class . '.php'; }); $app = new App($conf
<?php
namespace System;
require_once 'App/Config.php';
spl_autoload_register(function($class) use ($config) {
require_once $config['app']['root'] . '/' . $class . '.php';
});
$app = new App($config);
$app->Start();
?>
好的,很好!但是现在,我想建立数据库连接。我在数据库类中扩展了“App”类。如下图所示:
<?php
namespace System\Librarys;
use System\App;
class Database extends App
{
public function __construct()
{
parent::__construct(??? HOW DO I GET THE VARIABLE FROM THE "APP" CLASS ???);
var_dump($this->config);
}
}
?>
现在,如果我在
$this->config
上执行var\u dump()
,它将返回null
。这很清楚,因为我没有在父构造函数中传递$config var
。但是我该怎么做呢?我想设置应用程序
类中的所有变量,以便扩展它,而不需要将变量传递给其他类。我不清楚为什么在数据库
类中不使用相同的构造函数。
代码如下所示:
public function __construct($config)
{
parent::__construct($config);
}
然后在App
class中
$this->connection = new Database($this->config);
顺便说一句,如果您不打算向数据库
构造函数添加更多代码,那么实际上您并不需要它
附言。
我在你的代码中看到了糟糕的类设计。您可能正在使用App
类进行全局配置,数据库连接是其中的一部分。因此,您需要创建一个类来处理所有数据库操作。然后您只需在应用程序的实例中使用它。例如:
class DB {
function connect() { /* Some code */ }
// More functions
}
class App {
protected $db;
// contructorts etc
function run() {
$this->db = new DB(/* some config */);
// use it
}
}
在数据库
上调用\uu construct()
时,无法从应用程序
获取$this->config
,因为它尚未设置
必须先在构造函数中设置变量,然后才能使用它
class Database extends App
{
public function __construct()
{
parent::__construct("localhost");
var_dump($this->config); // $this->config is now "localhost"
}
}
你需要将它传递到数据库类中。我尝试的是在App类中设置所有变量,然后通过扩展的“App”类在数据库类中访问它。扩展不是这样工作的。顺便说一句,复数库是LibrariesOk,这是一个细节。但是我该怎么做呢?有没有一种方法可以访问变量而不在每个类中传递它?我知道静态变量,但这不是很好的做法。是的,我知道这一点,但你知道我有很多类,通过每个类传递变量是很困难的,我的意思是有没有一种简单的方法可以做到这一点,没有静态变量?见编辑后的答案。如果您有很多类,并且必须在整个结构中传递一些var,那么您的类设计就很糟糕。
class Database extends App
{
public function __construct()
{
parent::__construct("localhost");
var_dump($this->config); // $this->config is now "localhost"
}
}