Jeff
Jeff

Reputation: 6120

How does PHP process functions in a file?

Say I have file.php with three functions and an echo statement:

function one() {
    return three() . ' This is one.';
}

function two() {
    return 'This is two.';
}

function three() {
    return 'This is three.';
}

echo one(); // string(xx) "This is three. This is one."

First, is it generally acceptable to have function one() call function three() even though function three() appears later in the file?

Second, when file.php is loaded in the browser (thus executing the PHP on the server), does PHP calculate the return value of function two(), even though it is never called?

Any links for further reading on how PHP process mundane things like this would be great.

Upvotes: 0

Views: 212

Answers (5)

Brandon Henry
Brandon Henry

Reputation: 3719

by the time one() gets called, three() has already been defined, so no problem.

two() would not be evaluated until you call two().

http://www.php.net/manual/en/functions.user-defined.php

Upvotes: 0

erenon
erenon

Reputation: 19118

The order of function or class declaration doesn't matter. The only point is to declare before call. If two wont be called, it will be parsed but not evaulated.

Upvotes: 0

gnud
gnud

Reputation: 78548

PHP looks up class and function names when they are used at runtime, not according to when the code in question is parsed for the first time.

So, running three() inside one() is OK, as long as the function declaration of three() is parsed before one() is run for the first time.

Upvotes: 1

Peter Bailey
Peter Bailey

Reputation: 105898

First, is it generally acceptable to have function one() call function three() even though function three() appears later in the file?

Certainly. The source-order has no bearing on the order in which you call functions - it's all parsed and available before the first line is executed.

Second, when file.php is loaded in the browser, does PHP calculate the return value of function two(), even though it is never called?

No. It will be checked for syntax errors during parsing, but that's it - these will be E_PARSE level errors. Other errors are only discoverable at runtime and will be E_ERROR, E_WARNING, or E_NOTICE level errors.

https://www.php.net/manual/en/errorfunc.constants.php

Upvotes: 7

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

For your second question the answer is NO, it does not run the function unless it is specifically called. And it does not matter which order the functions are written in so the code you have will work.

PHP is not run in the browser, it is run by the server.

Upvotes: 1

Related Questions