构造函数声明数据库连接在 PHP 8 升级后不运行

问题描述 投票:0回答:2

连接数据库时出现错误。 在托管网站决定删除 php 7 并添加 php 8.3 之前,它一直在工作

这是连接函数的代码:

class App {

    function App() {
        include('dbInfo.php');
        try {
            $this->dbConn = new PDO("mysql:host=$host;dbname=$dbName",$dbUser,$dbPass, array(
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_PERSISTENT => true
              ));
        } catch (\Throwable $e) {
            die("ERROR: ".$e->getMessage());
        }
    }

    function getAll() {
        $config = $this->getConfig();
        $services = $this->getServices();
        $projects = $this->getProjects();
        $prices = $this->getPrices();
        return array('config'=>$config,'services'=>$services,'projects'=>$projects, 'prices'=>$prices);
    }
    function getPrices() {
        $sql = $this->dbConn->prepare('SELECT * FROM `prices`');
        $sql->execute();
        $result = $sql->fetchAll();
        return $result;
    }
    function getConfig() {
        $sql = $this->dbConn->prepare('SELECT * FROM `config`');
        $sql->execute();
        $result = $sql->fetchAll();
        return $result;
    }

}

这是错误消息:

警告:未定义的属性:App::$dbConn in /customers/b/b/1/944.dk/httpd.www/server/dataBase/myServer.php on line 29
Fatal error: Uncaught Error: Call to a member /customers/b/b/1/944.dk/httpd.www/server/dataBase/myServer.php:29 中的 null 函数 prepare() 堆栈跟踪:
#0 /customers/b/b/1/944。 dk/httpd.www/server/dataBase/myServer.php(16): App->getConfig()
#1 /customers/b/b/1/944.dk/httpd.www/server/templates/get.php (5): App->getAll()
#2 /customers/b/b/1/944.dk/httpd.www/server/index.php(3): include_once('/customers/b/b/. ..')
#3 {main} 在第 29 行的 /customers/b/b/1/944.dk/httpd.www/server/dataBase/myServer.php 中抛出

第29行是这样的:

$sql = $this->dbConn->prepare('SELECT * FROM `config`');
php database pdo
2个回答
3
投票

PHP 8.0开始,与类同名的方法不再被视为构造函数:

class Bar {
    public function Bar() {
        // treated as regular method in PHP 8.0
    }
}

这就是为什么你的函数

App()
从未运行来创建
$this->dbConn
.

您需要将其重命名为

function __construct()
以使其成为构造函数。


编辑:之前参考 PHP 5.3.3 的更改。 PHP 5.3.3 的更改仅影响名称空间类。 PHP 8.0 上的更改会影响没有命名空间的类的事件。


2
投票

function App() {
是老式的
__construct

在 PHP8 中,它不再被自动调用 - 导致类参数丢失。

function App()
重命名为
public function __construct()
.

检查Old-style constructors

© www.soinside.com 2019 - 2024. All rights reserved.