ViDiVe
ViDiVe

Reputation: 134

PHP function in function (no OOP) works weird

I'm not in OOP and I would like understand why in the procedural mode I can declare a function nestled in a function without errors, but I can call the nestled function from the "main" and cannot call from the primary function?

Example 1: calling b() in a() gives Fatal error / Why a() doesn't views b() ?

<?php
function a(){
  // do something
  b(); //Fatal error: Call to undefined function b()

  function b(){
    // do something
  }
}

a();

Example 2: calling b() from the main gives Fatal error (this is logic)

<?php
function a(){
  //  do something

  function b(){
    // do something
  }
} 

b(); // Fatal error: Call to undefined function b()

Example 3: calling a() and then calling b() from the main doesn't give error

<?php
function a(){
    //  do something

    function b(){
        // do something
    }

}

a();
b();

Upvotes: 0

Views: 61

Answers (1)

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

PHP is a procedural programming language. It will do each line, in order. The reason you can't call b() from within a() is because, at that point, b() has not been declared. What you want to do is declare your function before calling it:

<?php
function a(){
  // do something

  function b(){
    // do something
  }
  b(); 

}

a();

This is still bad practice though. Break b() out of a() :

<?php
function a(){
  // do something

  b();

}
function b(){
  // do something
}

a();

This will allow you to call a() and b() at any time.

Upvotes: 3

Related Questions