views:

41

answers:

4

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+.

+5  A: 

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.

Brad F Jacobs
Otherwise the constant value would change (!) from file to file.
Mchl
Is there anywhere where this is documented?
AlexV
Plenty of places. See the updated information I added for links the the PHP Manual which documents constants. As to what Mchl was referring to, that is not necessarily true. Once a constant is defined it should not be re-defined by it's nature and if you do it will throw a notice error. (See quote excerpt above) But Constants should stay...well constant.
Brad F Jacobs
Yes I know what a constant is. What I want to know is about code execution. PHP is the only language I used that allow functions and all kind of stuff in a const.
AlexV
OK I tested it with define('RND', rand(1, 1000)); and echoing RND multiples of times and it stay the same (for the same page load) which is what I expected.
AlexV
+1  A: 

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.

Hammerite
+1  A: 

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.

Wrikken
+2  A: 

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

Christian Smorra