简体   繁体   中英

PHP - Calling a function in another class

I have a class which is called connection.php which has all the stuff related to connecting to my database, it also has the following function:

function connect() {
    $pdo = new PDO('mysql:host='.$host.';dbname='.$db.'', $user, $pw);
}

When I try and call this function in another class in the example below:

require('connection.php');
try {
    $connect();

} catch (PDOException $e) {
    die("Error, could not connect.");
}

This give me the following error:

Fatal error: Function name must be a string in /home/[redacted]/public_html/[redacted]/authenticate.php on line 4

What am I doing wrong?

try

require('connection.php');
try {
    connect();

} catch (PDOException $e) {
    die("Error, could not connect.");
}

if you write $connect(); it will check for the variable $connect which is not being initialize so thats why you are getting the error

if you do like this

require('connection.php');
$a = 'connect';
try {

    $a();

} catch (PDOException $e) {
    die("Error, could not connect.");
}

this will work Because in place of variable $a connect will be placed and then it will search for the function connect(); I hope this will help you to understand better

Just to complement what Aman said here... You said you have a class that contains the function connect() but I don't see either a class definition or any indication that you're instantiating a new class either.

So let's say it really is in a class

class database {
    function connect() {
       $pdo = new PDO('mysql:host='.$host.';dbname='.$db.'', $user, $pw);
    }
}

You need to create an instance of this class now to use it. So we do the following

$db = new database();
try {
    $db->connect();
} catch (PDOException $e) {
    die("Error, could not connect.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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