简体   繁体   中英

Define a constant function call

My code is like this:

<?php
define("ERROR", "SOMETHING WRONG WITH MY DATABASE");
... 
if (!mysql_query($q)){
  die(ERROR);
}
?>

Now I want to replace "SOMETHING WRONG WITH MY DATABASE" with mysql_error() in case I want to debug it. what is the easiest way ?

This does not seem to work work: define("ERROR", mysql_error());

---- edit ---

I don't want to use mysql_error() under production environment, it may help the attacker figure out something related to my database? That's my point of using a constant string

as in C you can do #define x yourfunction() I'm not sure if I can do the same in php

The simple answer is "you cannot do that". The whole point of constant is that it's constant as in its value is never changed . If it refers to a function call, the function can return any value - and it's not constant any more.

One trick you can do is define the function call itself to be the value of the constant - and then eval it on demand, something like this:

define("ERROR", "return mysql_error()");
...
die(eval(ERROR));

However this is really a rather bad code. You'd be much better off doing

die(mysql_error());

A constant should be exactly what the name implies - constant . You cannot redeclare a constant, and anything that has a variable value should be stored in - you guessed it - a variable .

However, you could do something like this:

<?php

  define("ERROR", "SOMETHING WRONG WITH MY DATABASE: ");

  // ... 

  if (!mysql_query($q)){
    die(ERROR . mysql_error());
  }

?>

mysql_error() has to be called AFTER the sql operation that you are trying to catch. You cannot catch this error with a predeclared constant or variable. You either have to call it directly, or call another function which calls it, like so:

die(mysql_error());

or:

define("ERROR", "Database Problem ");

function Err() {
  $sql_err = ERROR . mysql_error();
  return $sql_err;
}
// sql operation here, then test for error
die(Err());

You can use something like Stefan suggested and add a DEBUG constant which you can switch between prod and dev environment:

define('DEBUG', 1);

// In the function:
// ...
echo ERROR;

if (DEBUG){
  echo mysql_error();   
}

die();

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