How to call a PHP function (with parentheses)

How to call a function in PHP

A reader of my blog recently emailed me, asking me to check over some PHP code

Nothing works from my php file except just connecting to the database

It’s simple code – I’m not doing anything fancy

So here’s the PHP code supplied:

function getConnection( ) {

$host="host";
$port=3306;
$socket="";
$user="me";
$password="mypassword";
$dbname="downloads";

@ $con = new mysqli($host, $user, $password, $dbname, $port, $socket);

if ( mysqli_connect_errno()) {
echo "Connection function failed";
return false;

} else {
echo "Connection function succeeded";
return $con;
}
}

$res = getConnection;
if (!$res) {
echo "Connection failed. " . mysql_errno($res) . ": " . mysql_error($res). "\n";
}
else {
echo "Connected to database." . "\n";
}

$key = md5(microtime());
if ($result = $res->query("SELECT count(*) FROM downloads WHERE downloadkey = '{$key}' LIMIT 1")){
echo "Select succeeded." . "\n";
}
else
{
echo "Select failed." . "\n";
}

They helpfully supplied output and the error message too:

Connected to database. Fatal error: Call to a member function query() on a non-object in /path-to/filename.php on line 33

Which seems to suggest to the connection is fine, but when it comes to use the connection. The connection object isn’t actually an object.

They are using a function to create the database connection, a good sign.

There are a few lines after the function, they all look okay

But wait, maybe something doesn’t look right about this line:

$res = getConnection;

Notice anything missing?

Does it look better like this?

$res = getConnection();

Yes! Calling a PHP function, even though that function has no parameters, you must include the parentheses!

Otherwise PHP doesn’t know it’s a function and actually assumes getConnection is a string. As demonstrated by this snippet:

$res = getConnection;
var_dump($res);
// Outputs: string(13) "getConnection"

So that was the first problem, the reader assumed the connection was being created.

When in fact the function was never being called.

Even though they have code to check the connection.

However, that code:

if (!$res) {

Was never going to equate to false, as $res was actually a string “getConnection”.

That if statement should be changed to this:

if (!is_object($res)) {

Now we are actually checking whether the $res variable is actually a connection object or not!