11

Consider this snippet:

function f() {
    return 'hi';
}

echo f();

Vs this snippet:

echo f();

function f() {
    return 'hi';
}

When I run the scripts, they both produce the same results. That's great.

But my question is (and I could not find a good answer or reference in any of my searches), is it okay to call the function before it is defined (ie, from a sequential parsing of the script file perspective)?

I don't want to run into any issues or deprecation down the road if I leave the function call ahead of the function definition block in my script file.

8
  • 1
    Is it THAT hard to test it yourself? To put this very code example into php file and run it? Commented Dec 6, 2010 at 15:52
  • 4
    He tested it wise-guy. When I run the script, they both produce the same results. That's great. He is just worried about deprecation. Commented Dec 6, 2010 at 15:55
  • 2
    @Col. Shrapnel: In other languages, yes. But PHP has many many quirks, so although his example works (which he did test himself), there's a chance that under some obscure circumstances something similar doesn't work. Or that the whole feature gets deprecated. Commented Dec 6, 2010 at 15:55
  • Thats quite stupid way of asking questions. One can generate it in thousands. "Should I use . for concatenations or it's going to be replaced with +?" "Aren't quotes going to be deprecated", etc. Every question should have at least a slightest reason, not being taken completely out of nowhere. Commented Dec 6, 2010 at 16:00
  • 1
    I think Col. Shrapnel needs a Hug Commented Dec 6, 2010 at 16:10

5 Answers 5

12

From the Manual:

Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

The possibility to call (reference) a function before it is defined is a PHP intentional feature and I don't think you need to worry about it becoming deprecated.

As an observation, if you can choose from declaring the function before or after, it would be common sense to declare it before it's used.

Note: The following code will give a fatal error because the function will only be defined at run rime.

<?php
echo helloWorld();
if(1){
    function helloWorld() {
        return 'hello world';
    }
}
?>
Sign up to request clarification or add additional context in comments.

7 Comments

Excellent Alin...did not catch that paragraph in the PHP Manual...that answers my question
Alin...you present an interesting if() statement. Can you explain the significance and purpose of if(1) ? Thanks (never seem that before -- and I love to learn new things all the time.)
I put that if to demonstrate the different behavior of functions defined conditionally. Even if the code may seem to be equivalent to your SAMPLE B, by putting the function declaration inside an if you determine it to be declared when the script reaches that if, and not before the script starts, as it happens in the other cases.
What I was actually curious about was he significance of if(1) ... it that the equivalent of a "universal truth" clause or does the "1" signify something like "run time"... I have just never seen that if() statement before.
@DrDOT: 1 always evaluates to true so the block of the if statement is always executed (there is no other "hidden" meaning). This construct itself is useless but helps to demonstrate the point of conditional definition here.
|
1

compiler steps are like so:

  • Converts a sequence of characters into tokens
  • Analyses the tokens to determine there Grammatical structure.
  • Generates byte code depending on the outcome of the analyses

So the easiest way to understand this is just because the script is not multi threaded does not mean its processed in one in line execution.

PHP Reads your entire source code into tokens before its executed, there for it has control over the order of tokens should be executed first.

Take this example

while(true)
{
    print '*';
}

Each line is a sequence of characters, so PHP Would interpret this as

if          #T_IF
            #T_WHITESPACE
(
            #T_WHITESPACE
true        #T_STRING
            #T_WHITESPACE
)
            #T_WHITESPACE
{
            #T_WHITESPACE
print       #T_PRINT
            #T_WHITESPACE
'*';        #T_CONSTANT_ESCAPED_STRING
            #T_WHITESPACE
}

but just because its been read does not mean its been executed.

So that functions are at the top of the list, this way you can execute them because there already within the systems memory.

I believe that the reason for this is that PHP's native library such as PFO,mysql_connect functions and classes are loaded first, and they move all user defined scopes to be loaded after there native implementations.

there loaded at the beginning of execution.

Comments

0

This is such a great question. Because it doesn't have a really good answer. PHP will, if given the chance, work just fine doing it backwards. Until it doesn't. And it won't if, for example, the function is defined in a yet-to-be loaded included file later on. PHP will include those files as they happen in code, so you will get a function not defined error in that case.

This is one SERIOUS gotcha in PHP.

It helps to imagine that includes are like copy/pasting whatever was in the other file into the code. But that it only happens when they get run in code. Which means they can be dynamic and based on the running code. But it also means they can't be pre-processed and linked up before-hand.

3 Comments

A: He did run it. B: He wasn't asking if it would work. C: it is a great question because it exposes something that is a big gotcha in PHP. D: You should learn to read what people say and stop being a jerk-face.
@Col. Shrapnel: Your comment might be justified or not, but posting it twice is sure unnecessary.
With all due respect Colonel, don't you have better things to do with your time that sit on stackoverflow and "snipe" at people trying to learn ?
0

I find it a good practice to first define my functions and later call them, but it doesn't matters where do you put them as long they're there ;)

Also, i like to have my functions separated in different php files, depending on the use, just to be organized :)

1 Comment

I too have many, many includes/requires throughout. Makes script files easier to read when you are simply looking at blocks of code that serve certain purposes.
-1

No matter where you define your function and where you call. Because as far as I know, PHP server application first reads the whole page then executes it.

3 Comments

As far as I know, there are cases where this doesn't work (let's wait for the PHP gurus' answers...).
@delnan Functions defined conditionally. See my answer.
Yea...I was really wondering if that is how the parsing engine preformed. I too an curious on Guru's 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.