扩展类变量(PHP)


Variables of extended class (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($config);
$app->Start();
?>

一切正常。现在我在类App的构造函数中传递了配置文件。

<?php
namespace System;
use System'Librarys'Database;
class App
{
  protected $config;
  protected $connection;
  public function __construct($config)
  {
    $this->config     = $config;
    $this->connection = $this->getConnection();
  }
  public function getConnection()
  {
    $this->connection = new Database;
    $this->connection = $this->connection->Connect();
    return $this->connection;
  }
  public function Start()
  {
    echo 'test';
  }
  public function __destruct()
  {
    $this->config     = null;
    $this->connection = null;
  }
}
?>

好的,一切都好!但现在,我想建立数据库连接。我在数据库类中扩展了"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_dump()操作,它返回null。这很明显,因为我没有在父构造函数中传递$config var。但我该怎么做呢?我想在App类中设置所有变量,以便我可以扩展它,并且不需要将变量传递给其他类。

我不清楚为什么你只是不使用Database类相同的构造函数。代码应该是这样的:

public function __construct($config)
{
   parent::__construct($config);
}

然后在App class

$this->connection = new Database($this->config);
顺便说一下,如果您不打算向Database构造函数添加任何代码,则实际上不需要它。

注:我在你的代码中看到了糟糕的类设计。您可能正在使用App类进行全局配置,数据库连接是其中的一部分。因此,您需要创建一个类来处理所有数据库操作。然后在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
    }
}

当你在Database上调用__construct()时,你不能从App中获得$this->config,因为它还没有设置。

你必须在构造函数中设置变量才能使用它。

class Database extends App
{
    public function __construct()
    {
        parent::__construct("localhost");
        var_dump($this->config); // $this->config is now "localhost"
    }
}