扩展的pdo连接返回null

时间:2015-07-15 16:32:22

标签: php model-view-controller pdo connection extends

我有问题。我有2个类(RouteController和BaseController)。在类BaseController中我包含了我的pdo连接,并且工作正常。在RouteController类中,我扩展了BaseController,我希望连接也可以在RouteController类中使用。但是如果我创建一个var_dump()它返回NULL。我怎样才能使它有效?

的index.php:

<?php

ini_set('display_errors', true);
error_reporting(E_ALL);

require_once 'App/Config.php';
require_once 'App/Controllers/BaseController.php';
require_once 'App/Controllers/RouteController.php';
require_once 'App/Controllers/DatabaseController.php';

$connection = new DatabaseController($config['database']['host'], $config['database']['user'], $config['database']['pass'], $config['database']['name']);
$connection = $connection->Connection();

new BaseController($connection);
new RouteController;

以下是课程:

DatabaseController

<?php

class DatabaseController
{
  private $host;
  private $user;
  private $pass;
  private $name;

  public function __construct($host, $user, $pass, $name)
  {
    $this->host = $host;
    $this->user = $user;
    $this->pass = $pass;
    $this->name = $name;
  }

  public function Connection()
  {
    try {
      $this->db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->name, $this->user, $this->pass);
      $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
      $this->db->exec("SET CHARACTER SET utf8");
      return $this->db;
    } catch(PDOException $e) {
      die($e->getMessage());
    }
  }
}

BaseController

<?php

class BaseController
{
  protected $connection;

  public function __construct($connection)
  {
    $this->connection = $connection;
  }
}

RouteController

<?php

class RouteController extends BaseController
{
  public function __construct()
  {
    var_dump($this->connection); // Return NULL
  }
}

我需要一些帮助,谢谢。 抱歉我的英语不好。

1 个答案:

答案 0 :(得分:0)

尝试使用此代码:

<?php

class RouteController extends BaseController
{
  public function __construct($connection)
  {
    parent::__construct($connection);
    var_dump($this->connection); // Return NULL
  }
}

$myObject = new RouteController($con);

更新:

<?php 

class BaseController
{
  private $connection;

  public function __construct($connection)
  {
    $this->connection = $connection;
  }

  public function getConnection() {
      return $this->connection;
  }
}

class RouteController extends BaseController
{
  public function __construct($connection)
  {
    parent::__construct($connection);
    /* some other construct code */
  }
}

$test = 'hello';
$myObject = new RouteController($test);
var_dump($myObject->getConnection());

这项工作