从父类访问属性,在构造函数中分配时返回null

时间:2015-02-10 09:56:07

标签: php oop

我试图从控制器类process_loginController中的类adb访问属性mysqli,只是$this->mysqli返回null,而不是boolean true(连接到数据库)。在process_loginController.php我有处理登录的脚本,但是当我登录时,我得Fatal error: Call to a member function prepare() on a non-object in cf.class.php on line 3 if ($stmt = $this->mysqli->prepare("SELECT....")) {。我在cf.class.php中为$this->mysqli做了一个var_dump,它返回null

adb.class.php

class adb{
    public $mysqli; // this properties cannot be accessed 
    public $db;
    public $sql_details;
    public $hello_there;
    public function __construct() {
        $this->mysqli = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
        $this->db = PDOManager::getInstance();
        $this->hello_there = '123';
    }
    public function url(){ // this function can be accessed
        $url = 'http://www.example.com';
        return $url;
    }
}

cf.class.php

class cf extends adb {
    public function login($email, $password, $db) {
      if ($stmt = $this->mysqli->prepare("SELECT....")) {
         // some code here
      }
    }
}

controller_base.class.php

Abstract Class baseController extends cf {

    protected $registry;
function __construct($registry) {
    ob_start();
    $this->sec_session_start();
    $this->title_of_page();
    $this->registry = $registry;
    $this->registry->template->is_logged_in = ($this->login_check($this->mysqli) !== false) ? true : false; // this returns what should return so it's ok
}
abstract function index();

}

process_loginController.php

Class process_loginController Extends baseController {

    public function index() {
        if (isset($_POST['email'], $_POST['p'])) {
            $email = $_POST['email'];
            $password = $_POST['p']; // The hashed password.
            if ($this->login($email, $password, $this->mysqli) == true) {
                // Login success 
                header('Location: ../');
            } else {
                // Login failed
                header('Location: index.php?rt=signin?error=1');
            }
        } else {
            // The correct POST variables were not sent to this page. 
            echo 'Invalid Request';
        }
    }
}

我也尝试了一件容易的事情:

hello.php

require 'model/adb.class.php';
require 'model/cf.class.php';
class hello extends cf {
    public function hello() {
        var_dump($this->mysqli); // should have returned true instead NULL
        var_dump($this->url()); // this one is accessed and returns ok `example.com`
        var_dump($this->hello_there); // should have been 123 instead is NULL
    }
}
$conect = new hello;

由于某些原因,这些属性无法访问,但功能是并且不了解原因。

1 个答案:

答案 0 :(得分:3)

您永远不会打电话给您的父母__construct()。因此,你的mysqli永远不会创建,并且是,是null

我知道这不是codereview。但是你应该从不使用公共属性。只是

您还应该对代码进行折射以使用依赖注入。现在,每个cotnroller都有一个不同的mysqli对象,而不是共享相同的资源。

你的方法也做得很多,他们做的东西,他们处理错误,他们回应输出给用户,他们做一些重定向,...保持愚蠢简单,并去单一责任