frankenphp icon indicating copy to clipboard operation
frankenphp copied to clipboard

global on Function

Open robbieyannor13 opened this issue 10 months ago • 5 comments

Since I enabled FrankenPHP worker mode, all global variables within functions have stopped working. For example:

function conn($params) {
  global $conn;
  // ... ;
}

What is the solution without adding the connection as a parameter to conn($conn, $params)? As it would be very difficult to change everything.

robbieyannor13 avatar Mar 11 '25 16:03 robbieyannor13

(Un-?)fortunately worker mode does require a few changes to your code. I wasn't aware global variables were a problem, though. Do they already fail on the very first request? It's possible that the variable is overwritten somewhere and then the next request won't have it initialised.

henderkes avatar Mar 12 '25 01:03 henderkes

(Un-?)fortunately worker mode does require a few changes to your code. I wasn't aware global variables were a problem, though. Do they already fail on the very first request? It's possible that the variable is overwritten somewhere and then the next request won't have it initialised.

I tried creating a simple line of code like this to confirm my intended purpose.

$mysqli = new mysqli('mysqli', 'root', 'pass', 'db');

function row($table){   
    global $mysqli;
    $result=mysqli_query($mysqli,"SELECT `id` FROM `$table`;");
    return mysqli_num_rows($result);
}

echo row('users');

The result will display the following error message: Fatal error: Uncaught TypeError: mysqli_query(): Argument #1 ($mysql) must be of type mysqli, null given in /index.php

However, if I change it like this, the function will work.

function row($mysqli,$table){   
    $result=mysqli_query($mysqli,"SELECT `id` FROM `$table`;");
    return mysqli_num_rows($result);
}

echo row($mysqli,'users');

robbieyannor13 avatar Mar 12 '25 01:03 robbieyannor13

If you disable opcache, does it work? I'm chasing down a fun bug with opcache.

Also, did you check that $mysqli actually has a value?

withinboredom avatar Mar 12 '25 11:03 withinboredom

If you disable opcache, does it work? I'm chasing down a fun bug with opcache.

Also, did you check that $mysqli actually has a value?

I have tried to disable OPcache, but it's still the same.

$test = 'abc';
function test(){
  var_dump($test);
}
test();

its given NULL

I found a temporary alternative that works.

$GLOBALS['test']='abc';
function test(){
  var_dump($GLOBALS['test']);
}
test();

robbieyannor13 avatar Mar 12 '25 13:03 robbieyannor13

The issue might be that the variable is not in global scope when you declare it, you can also do something like this:

function conn($params) {
  global $conn;
  if (!isset($conn)){
    $conn = ...
  }
  return $conn;
}

AlliBalliBaba avatar Mar 12 '25 21:03 AlliBalliBaba