skip to Main Content

I am getting an error when I connecting to database.
It was working before the hosting website decide to remove php 7 and add php 8.3

This is the codes of the connection function:

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 getConfig() {
        $sql = $this->dbConn->prepare('SELECT * FROM `config`');
        $sql->execute();
        $result = $sql->fetchAll();
        return $result;
    }

}

And this is the error msg:

Warning: Undefined property: 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 function prepare() on null in /customers/b/b/1/944.dk/httpd.www/server/dataBase/myServer.php:29 Stack trace:
#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} thrown in /customers/b/b/1/944.dk/httpd.www/server/dataBase/myServer.php on line 29

The line 29 is this:

$sql = $this->dbConn->prepare('SELECT * FROM `config`');

2

Answers


  1. From PHP 8.0 on, method with the same name as the class is no longer treated as constructor:

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

    That’s why your function App() was never run to create the $this->dbConn.

    You need to rename it as function __construct() to make it a constructor.


    Edit: Previously refer the change to PHP 5.3.3. The change on PHP 5.3.3 only affected namespace classes. The change on PHP 8.0 affects event the class without namespace.

    Login or Signup to reply.
  2. function App() { is old style __construct

    In PHP8 it is no longer called automatically – leading to missing class parameter.

    Rename function App() to public function __construct().

    Check Old-style constructors

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search