1

I am using old code for a login process that accesses a local database. This is the first web project that I would like to put online. The code that I started with had deprecated functions so I've been trying to get everything up and running and gain an understanding of the language/process.

The original developers used a variable $link and two lines later they declare a global $$link. (EDIT: Since I first posted I learned about a variable variable, but I still fully understand this use case. What could it be used for)

tep_db_connect() or die('Unable to connect to database server!');
function tep_db_connect($server = DB_SERVER, $username = DB_SERVER_USERNAME, $password = DB_SERVER_PASSWORD, $database = DB_DATABASE, $link = 'db_link')
{
  global $$link;

  $$link = new mysqli($server, $username, $password);

  if (!$$link) {
  die("Connection Failed: " . $mysqli_connect_error());
  }

 mysqli_select_db($$link, $database);
 return $$link;

}

This is my first web project. I'm used to using a debugger to figure things out.

Jordan
  • 38
  • 1
  • 7
  • 2
    It's a [variable variable](http://php.net/manual/en/language.variables.variable.php)... if the value of `$link` is the string `db_link`, then it will create a new variable `$db_link` (and assign the new mysqli instance to that new variable.... though why it's being used here is unknown – Mark Baker Feb 14 '18 at 16:43
  • 1
    Possible reason why: Its (a simple way) you can setup multiple database objects without smashing a single variable. You do a tep_deb_connect with a new link name, to setup a second connection (possibly to a second database). Old old mysql object wrappers used to be like this, usually with a lot of those canned-forum packages out there. Many many years ago. – IncredibleHat Feb 14 '18 at 16:51
  • I'm pretty sure `tep_*` functions are the default in OSCommerce... which is about a bazillion years old and this kinda looks like code from that, [for example](https://forums.oscommerce.com/topic/366663-question-about-tep_db_connect/), you probably wouldn't do anything like this with new code. – CD001 Feb 14 '18 at 16:53
  • @CD001 one site I maintain still does! Course its 19 years old now... and I've not been paid enough to rewrite it all ;) lol but yeah... – IncredibleHat Feb 14 '18 at 16:55

1 Answers1

3

I believe this can be considered "meta" programming, but as has been mentioned, this is a variable variable. An example to illustrate may be:

$a = '1';
$b = 'a';
echo $$b; // result: 1, can effectively be read as ${$b} -> ${a} -> $a
echo ${$b}; // same as above but a bit more obvious