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();
1 Answer 1
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.
-
Thanks, now I've understood!ViDiVe– ViDiVe2018年03月27日 13:35:46 +00:00Commented Mar 27, 2018 at 13:35
a()
once during the whole execution of your script.b()
is only declared once you first calla()
, and will raise an error about redeclaring an existing function if you ever calla()
again. Both functions will be declared in global scope, which isn't necessarily obvious.