无法访问父字段

时间:2017-03-27 18:48:05

标签: php

我现在正在学习一些PHP,作为练习,我正在编写一对非常简单的数据库连接器类,带有echo语句:

<?php

class DBConnector {
    protected $hostname;
    protected $username;
    protected $db_name;
    protected $pass;
    protected $conn;

    function __construct($host, $user, $pwd, $db) {
        echo phpversion() . "<br>";
        $hostname = $host;
        $username = $user;
        $pass = $pwd;
        $db_name = $db;
        echo "parent constructor hostname: " . $hostname . "<br>";
        echo "parent constructor username: " . $username . "<br>";
        echo "parent constructor pass: " . $pass . "<br>";
        echo "parent constructor db_name: " . $db_name . "<br>";
    }
}

class MYSQLConnector extends DBConnector {

    function __construct($host, $user, $pwd, $db) {
        parent::__construct($host, $user, $pwd, $db);
        echo "child constructor hostname: " . $host . "<br>";
        echo "child constructor username: " . $user . "<br>";
        echo "child constructor pass: " . $pwd . "<br>";
        echo "child constructor db_name: " . $db . "<br>";
        echo "child accessing parent's hostname: " . $this->hostname . "<br>";
        echo "child accessing parent's username: " . $this->username . "<br>";
        echo "child accessing parent's pass: " . $this->pass . "<br>";
        echo "child accessing parent's db_name: " . $this->db_name . "<br>";
    }

    // Open connection to database
    function open_connection() {
        $this->conn = new mysqli($this->hostname, $this->username, $this->pass, $this->db_name);
        if($conn->connect_errorno) {
            return false;
        }
        return true;
    }

    // Send query to database
    function submit_query($query) {
        // nothing bad could ever happen with this
        return $conn->query($query);
    }
}

?>

但是,echo语句的结果如下:

5.5.38
parent constructor hostname: localhost
parent constructor username: web_connection
parent constructor pass: 1234
parent constructor db_name: test
child constructor hostname: localhost
child constructor username: web_connection
child constructor pass: 1234
child constructor db_name: test
child accessing parent's hostname: (nothing printed)
child accessing parent's username: (nothing printed)
child accessing parent's pass: (nothing printed)
child accessing parent's db_name: (nothing printed)

在调用构造函数时,父字段显然已设置,因此这不是问题。但是,尝试在子类中使用$this->访问父类的成员似乎并不像我期望的那样访问变量,并且不会导致输出。由于空白值传递到open_connection()

,调用new mysqli()会产生警告
Warning: mysqli::mysqli(): (HY000/1045): Access denied for user ''@'localhost' (using password: NO) in /Library/WebServer/Documents/classes/database_connectors/mysql_connector.php on line 39

我查看的所有文档都表明我的代码应该是正确的,将字段设置为protected不应该导致任何问题。将它们设置为public不会改变结果。我想我可以为这些字段编写一些getter方法,但如果我的理解是正确的话,我不应该在这种情况下 - 所以我在这里做错了什么?

这是在我的本地计算机上的Mac OSX(10.11.6)apache服务器上,PHP版本为5.5.38。

0 个答案:

没有答案