简体   繁体   中英

C++ #define in PHP

I realize that "eval" largely fills the role of the C++ #define feature, but how would I do something like this in PHP:

#define D(x,y) if (N==x) return(y); else {
void Sample(int N) {
  D(3)
    D(4)
      D(22)
    }
  }
}

My problem is that eval("return;") will just return from eval, not from the calling routine. My other problem is parameterizing the macro.

You could probably use a preprocessor (you'd need to write it yourself) which replaces the macro in your code.

However, I fail to see why you would need to use such things - is there something wrong with defining a function and using that?

Macro in PHP or in any other language that does not require to compile source code (like ASP) are useless. Macro were created in C/C++ to improve performances, but in languages like PHP they would only decrease performances.

They make sense in languages like C/C++ because the source code of your application is 1st preporcessed by the C preprocessor that converts macro into code, than the code is compiled in a monolithic stand alone working application (with .exe extension). Every time the .exe application is called the macro are not expanded again because they were already replaced before compliation thus improves the speed of the application.

In PHP the source code of your script does not need to be compiled 1st to work. As you know you place the source code of your PHP files direcly on to the server, and this last one takes care to compiles and run it on the fly on every client request. So it would be useless for a server to preprocces a macro and convert it into code and then process again all the code. It would result in worst performances because it would have to read source code twice.

They also opened a new feature request in the official PHP bugs site.

http://bugs.php.net/bug.php?id=46017

But obviously it was closed as "Won't fix"!!!

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