简体   繁体   English

定义一个常量函数调用

[英]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. 现在,我想用mysql_error()替换“用我的数据库写错了”,以防调试。 what is the easiest way ? 最简单的方法是什么?

This does not seem to work work: define("ERROR", mysql_error()); 这似乎无法正常工作: 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? 我不想在生产环境下使用mysql_error(),这可能有助于攻击者找出与我的数据库有关的东西? 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 如在C中,您可以#define x yourfunction()我不确定我是否可以在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: 您可以做的一招是将函数调用本身定义为常量的值-然后按需eval它,如下所示:

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. 在尝试捕获的sql操作之后必须调用mysql_error()。 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: 您可以使用类似于Stefan建议的内容,并添加一个DEBUG常量,您可以在prod和dev环境之间进行切换:

define('DEBUG', 1);

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

if (DEBUG){
  echo mysql_error();   
}

die();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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