简体   繁体   English

类中未定义的变量…但是我定义了它

[英]Undefined variable in class… but I define it

I'm trying to create a class for my database: class structure as below 我正在尝试为我的数据库创建一个类:类结构如下

<?php
    require_once("config.php"); // include(Username, passowrd, server and databaseName)
    class MySQLDatabase{
        private $connection;

        function __construct(){
            $this->openConnection();
        }

        public function openConnection(){
            $this->$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PWD, DB_NAME);
            if(!$connection){
                die("Database connection failed: ".mysql_error);
            }
        }

    }
    $database = new MySQLDatabase();
    $db =&$database;

 ?>

then my first step was check this weather work or not. 然后我的第一步是检查天气工作与否。 so I code index.php file as below 所以我将index.php文件编码如下

    <?php                   
require("../includes/database.php");                                       if(isset($database)){
echo "true";
}else{
echo "false";
}
    ?>

after that I run the program and I got errors as below. 之后,我运行该程序,但出现以下错误。 I can not understand the reason. 我不明白原因。 I google it and there are no clear solution for this. 我用谷歌搜索,对此没有明确的解决方案。 is there are anyone can help me to understand why this happen and how to solve this? 有没有人可以帮助我了解为什么会这样以及如何解决呢?

( ! ) Notice: Undefined variable: connection in C:\\wamp\\www\\waytoits\\includes\\database.php (!)注意:未定义变量:C:\\ wamp \\ www \\ waytoits \\ includes \\ database.php中的连接

on line 9
Call Stack
#   Time    Memory  Function    Location
1   0.0005  240792  {main}( )   ..\index.php:0
2   0.0008  249872  require( 'C:\wamp\www\waytoits\includes\database.php' ) ..\index.php:3
3   0.0013  250528  MySQLDatabase->__construct( )   ..\database.php:55
4   0.0013  250592  MySQLDatabase->openConnection( )    ..\database.php:15

( ! ) Fatal error: Cannot access empty property in C:\wamp\www\waytoits\includes\database.php on line 9
Call Stack
#   Time    Memory  Function    Location
1   0.0005  240792  {main}( )   ..\index.php:0
2   0.0008  249872  require( 'C:\wamp\www\waytoits\includes\database.php' ) ..\index.php:3
3   0.0013  250528  MySQLDatabase->__construct( )   ..\database.php:55
4   0.0013  250592  MySQLDatabase->openConnection( )    ..\database.php:15

You are using $this->$connection instead of $this->connection . 您正在使用$this->$connection $this->connection $this->$connection而不是$this->connection Remove the $ sign in connection and try again. 删除connection$符号,然后重试。

$this::$connection (with the $ preserved) would refer to a static variable. $this::$connection (保留$ )将引用一个静态变量。 Because you have a class variable you should access it via $this->connection 因为您有一个类变量,所以应该通过$this->connection访问

Also you need to use the same instructions in your if -statement. 另外,您还需要在if语句中使用相同的指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM