gpt4 book ai didi

php - 类中 undefined variable ......但我定义了它

转载 作者:太空宇宙 更新时间:2023-11-03 12:10:44 24 4
gpt4 key购买 nike

我正在尝试为我的数据库创建一个类:类结构如下

<?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;

?>

然后我的第一步是检查天气是否正常。所以我将 index.php 文件编码如下

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

之后,我运行程序,但出现如下错误。我不明白原因。我用谷歌搜索,没有明确的解决方案。有没有人可以帮助我理解为什么会发生这种情况以及如何解决这个问题?

( ! ) Notice: Undefined variable: connection 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

( ! ) 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

最佳答案

您正在使用 $this->$connection 而不是 $this->connection 。删除 $ 登录 connection 并重试。

关于php - 类中 undefined variable ......但我定义了它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24318639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com