简体   繁体   中英

How does PHP uses constants (defines)

Imagine I have this constant in PHP:

define('APP_PATH', str_replace('//', '/', str_replace('\\', '/', dirname(__FILE__) . '/')));

When I use APP_PATH in my application, does PHP execute the code ( dirname , and the two str_replace on __FILE__ ) each time or PHP execute the code once and store the result in APP_PATH ? I hope I'm clear enough :)

This question applies to PHP 5.1.0+.

It should be done once, at the time it was defined.

UPDATED For documentation: define() - constants

From the documentation:

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

If you want more information on constants go ahead and read the documentation, it is explained pretty well there and probably has usage examples.

if you want a variable rather than a function you could make this an anonymous function

$APP_PATH=function(){ return str_replace('//', '/', str_replace('\\', '/', dirname(__FILE__) . '/') }

or

$APP_PATH=function($file){ return str_replace('//', '/', str_replace('\\', '/', dirname($file) . '/') }

which you could call with $APP_PATH [without variables] or $APP_PATH( FILE ) depends on what you wanna do

It executes it once and stores the result in APP_PATH . From that point on, APP_PATH is a scalar value. It's not like a handle to a computation/function or anything.

Tt is stored as the outcome in a single request , at the moment of the define . Hence 'constant'. The next request / script invocation will run the code again, so between requests it could be inconsistent.

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