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


Accessing properties from parent class returning null while assigned in constructor

我正试图从控制器类process_loginController内的类adb访问属性mysqli,只是$this->mysqli返回null,而不是布尔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;

底线是,由于某些原因,这些属性是不可访问的,但函数可以访问,也不明白为什么。

您永远不会调用父级__construct()。因此,您的mysqli永远不会被创建,而是,yup null

我知道这不是代码审查。但是您应该永远不要使用公共属性。只是不要

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

你的方法也做了很多事情,它们做一些事情,处理错误,向用户回显输出,进行一些重定向。。。保持愚蠢简单,并选择单一响应