返回未定义的变量

时间:2014-02-12 02:29:25

标签: php oop

我很难理解这一点,

$ dbhost $ dbuser的值; $ DBPASS; $ DBNAME; $ DBConnection进行;已经直接在类名下声明,因此可以在整个类中访问它。

   class Database {

        protected  $dbhost;
        protected  $dbuser;
        protected  $dbpass;
        protected  $dbname;
        protected  $dbconnection;

    }

在构造函数(__ construct)中,使用$ this-> [variablename]初始化值,因此:

$dbhost = $this->dbhost = 'localhost';
$dbuser = $this->dbuser = 'root';
$dbpass = $this->dbpass = '';
$dbname = $this->dbname = 'forms_db';   
$dbconnection = $this->dbconnection = (mysql_connect($dbhost, $dbuser, $dbpass));       

预计新值将在其值已更改时存储在类变量中

但是,每当我使用其他方法访问值时,我都会收到未定义的变量错误。

这是我的其余代码:

<?php

class Database {

    protected  $dbhost;
    protected  $dbuser;
    protected  $dbpass;
    protected  $dbname;
    protected  $dbconnection;




    function __construct() {

        $dbhost = $this->dbhost = 'localhost';
        $dbuser = $this->dbuser = 'root';
        $dbpass = $this->dbpass = '';
        $dbname = $this->dbname = 'forms_db';   
        $dbconnection = $this->dbconnection = (mysql_connect($dbhost, $dbuser, $dbpass));       

         if(!$dbconnection) die("Could not connect to database. " . mysql_error());

        return ($dbconnection);
    }

function testing(){


                echo $dbhost;
                echo $dbuser;
                echo $dbpass;
                echo $dbname;
                echo $dbconnection;         


        }

}

$data = new Database();

$data->testing();

2 个答案:

答案 0 :(得分:1)

在你的测试方法中,你没有回应这些属性。

变化:

echo $dbuser;

要:

echo $this->dbuser;

对您尝试访问的所有媒体资源执行此操作。

答案 1 :(得分:0)

测试功能变为

function testing(){


                echo $this->dbhost;
                echo $this->dbuser;
                echo $this->dbpass;
                echo $this->dbname;
                echo $this->dbconnection;
        }

}

因为函数测试中未定义$ dbhost。