0

Example 1: Here I expect that function hello must be in the global scope. But as per my expectation it does not behave same.It does not put function hello into global scope. at run time php must put function hello into global scope. It says undefined function hello().

$fruit=true;

foo();

hello();

function foo()
{
    echo "you are in the foo<br/>";
}

if($fruit)
{

    function hello()
    {
        echo "you are in the hello<br/>";
    }
}

Example 2 : Now as after example 1 , i supposed the below script must also work as example 1. i supposed it will give also error undefined function bar(). But now here it behave differently and execute bar.

foo();


bar();

function foo() 
{
  function bar() 
  {
    echo "I don't exist until foo() is called.\n";
  }
}

So i am unable to get the concept how php interpreter behave internally. How does it parse the program, and does it execute the step one by one , or whole program at once?

2 Answers 2

2

I quote a manual for you:

When a function is defined in a conditional manner .... Its definition must be processed prior to being called.

And more:

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

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

1 Comment

I have gone through this manual before. i know what are you saying. But the thing is that i would like to know how it will interpret both example using hash table and stack. i would like to know internally. Means how php behaves run time
0

Example One:

You do not define the function hello() until a part of the script has run, its in an IF and therefore does not get defined until after you attempt to call it

Like this you get no errors as the IF is run before the now defined funtion hello is called. And of corse either way it is in the GLOBAL scope. But your way it didnt exist anywhere until after you called it.

<?php
$fruit=true;
if($fruit)
{

    function hello()
    {
        echo "you are in the hello<br/>";
    }
}
foo();

hello();

function foo()
{
    echo "you are in the foo<br/>";
}

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.