开发者

How does PHP process functions in a file?

开发者 https://www.devze.com 2022-12-11 14:21 出处:网络
Say I have file.php with three functions and an echo statement: function one() { return three() . \' This is one.\';

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开发者_StackOverflow() 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.


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.

http://us2.php.net/manual/en/errorfunc.constants.php


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.


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号