0

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.

0

5 Answers 5

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

I don't remember completely, but wasn't this added with PHP5, or was that something else (I'm referring to question one...)?
1

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.

Comments

1

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.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.