Does function definition order matter? - php

In the script below, does the order in which items are declared matter?
For example, if the add_action points to a function that has not yet been defined? Does it matter or should the function declaration always precede any code in which its called?
add_action('load-categories.php', 'my_admin_init');
function my_admin_init(){
//do something
}

That doesn't matter if the function is declared before or after the call but the function should be there in the script and should be loaded in.
This is the first method and it will work:
some_func($a,$b);
function some_func($a,$b)
{
echo 'Called';
}
This is the second method and will also work:
function some_func($a,$b)
{
echo 'Called';
}
some_func($a,$b);

From the PHP manual:
Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.
However, while this is more of a personal preference, I would highly recommend including all the functions you actually use in an external functions.php file then using a require_once() or include_once() (depending on tastes) at the very top of your main PHP file. This makes more logical sense -- if someone else is reading your code, it is blindingly obvious that you are using custom functions and they are located in functions.php. Saves a lot of guesswork IMO.

you can call a function before it's defined, the file is first parsed and then executed.

No.
It is not C :P...
As you can see here , the whole file is first being parsed and then executed.
If a function that doesn't exist is being called, php will throw an error.
Fatal error: Call to undefined function

As per my personal experience, In some special cases (Like, passing array's in function or function inside a function and so on). It's best option to define the function above the call. Because of this sometimes neither function works nor PHP throw an error.
In normal php functions, it doesn't matter. You can use both of the types.

It does not matter, as long as it is declared somewhere on the page.
as seen here:
http://codepad.org/aYbO7TYh

Quoting the User-defined functions section of the manual :
Functions need not be defined before
they are referenced, except when a
function is conditionally defined
So, basically : you can call a function before its definition is written -- but, of course, PHP must be able to see that definition, when try to call it.

Related

PHP include/require inside functions

Having functions that are quite big and they are loading every time the page is loaded, would be better to write function foo(){ include(.../file_with_function's_code); return; } to minimize the size of the functions script? Or it doesn't matter because when a function is loaded (but not executed) also is loaded the content even if it is into an include? Thank you.
(Edit: my question is not about if it's possible or not)
While #Luceos answer is technically correct (the best kind of correct), it does not answer the question you asked, namely is doing this better, or do includes happen regardless of function calls?
I tested this in the most basic way (OP, why didn't you?):
<?php
echo "Testing...";
function doThing() {
include nonExistantFile.php;
}
//doThing();
echo "Done testing.";
Results:
if I call doThing(); I get a file not found warning.
If I comment out doThing();... there is no error! So you can save file load time by doing this.
Or, as a good alternative, encapsulate your functions in classes, and take the benefit of __autoload :
function __autoload($class_name) {
include $class_name . '.php';
}
Encapsulate myBigFunction() in a class
class myBigFunction {
public static function run() {
//the old code goes here
}
}
save it as myBigFunction.php
When you call the function as static method on the class :
myBigFunction::run()
__autoload will load the file, but not before that.
Yes that's possible; see http://www.php.net/manual/en/function.include.php
If the include occurs inside a function within the calling file, then
all of the code contained in the called file will behave as though it
had been defined inside that function. So, it will follow the variable
scope of that function.
Question is, why not add the surrounding function definition to that included file. I think the only viable reason to include within a function is to split code within that function into bits.
Both Luceos' and Albatrosz could be misread, so I felt that I should clarify these.
The include set of directives generate a runtime ZEND_INCLUDE_OR_EVAL operation which calls the Zend compiler to compile the referenced file. So in general you should not embed include statements in a function, as:
The include will be executed every time that code path is taken when the function is called. Compiling the same bit of code 100s of times is a bad idea.
If the code contains elements of global scope (e.g. function or class declarations) then executing that declaration even twice will cause compiler errors.
So don't unless you know what you are doing. Use techniques such are those described by Albatrosz. Incidentally his __autoload() function is just the sort of example of an exception where this is valid to do.

media wiki. how did function get argument?

The question is about functions and arguments in PHP. I am reading code of simple extension for mediawiki.
It adds callback function:
$wgHooks['ArticleSaveComplete'][] = 'fnAutoWikiDump';
and then there is definition of this function:
function fnAutoWikiDump(&$article, &$user, &$text, &$summary, &$minoredit,
&$watchthis, &$sectionanchor, &$flags, &$revision){...}
inside this function I can access members of class $article:
$awd_title = $article->getTitle();
I cannot understand how variable $article was passed to the function while calling it? It looks like it was passed in definition of the function (I know it is wrong), but I don't understand how it was passed.
Do you?
The code you have posted, and the sample code in the link do not show the details of actually calling the function. It is merely registered as a callback. Part of the usefulness of callback functions is that you typically do not have to call them yourself at all, but rather they are called automatically by the process that uses them.
Somewhere else in the MediaWiki code, where the callbacks registered with ArticleSaveComplete are called (there's an array of them), the correct parameters are passed to the function call in a regular and recognizable function call or via a mechanism like call_user_func().
When defining a callback to work with that interface, your responsibility as a programmer is only to be sure that the function definition takes the correct number of parameters in the correct order, and with the correct names. The details of how it gets called are up to the mechanism that calls it.

PHP Function Call Placement

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.
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';
}
}
?>
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.
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.
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 :)
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.

Get a called functions list in PHP

In PHP, get_included_files() returns an array with the names of included files.
In a similar fashion, is there any way to get an array with the names of called functions with parameters?
In this way, Is any way to get an array with the names of called functions with parameters?
No.
What you can do is a debug_backtrace() which will show all the function calls (with parameters) that lead to the execution of the line you are doing the backtrace from (the "call stack"), but that's different from all functions that were ever called in the script.
What do you want to do? Maybe there's a different approach.
I was searching for something similar and found xdebug's tracing very useful.
Here's an example of how it could look like:
http://devzone.zend.com/1135/tracing-php-applications-with-xdebug/
I was trying to achieve what you want and finally came up with an reasonable solution.
Make a class named Debug and include that above every file you want to debug in. Build yourself a function that prints nicely the information stored in $calls.
class Debug {
private static $calls;
public static function log($message = null)
{
if(!is_array(self::$calls))
self::$calls = array();
$call = debug_backtrace(false);
$call = (isset($call[1]))?$call[1]:$call[0];
$call['message'] = $message;
array_push(self::$calls, $call);
}
}
Call this function everytime you declare a function first line in the functionbody: Debug::log($message(optional) )
Not that I'm aware.
You can however use debug_backtrace to get the currently active function/method hierarchy.
I don't think there's a way to do what you want. Sorry.
The closest I can get is the function_exists() function, which will tell you whether a specific function has been loaded.
What exactly do you want to achieve here? I can't see a use case (outside of a php_info() type screen) that would require a list of available functions.
You will have to install it as an extension, but a profiler like XHProf will give you a breakdown of which functions are called and how long they take, as well as a callgraph.
XHProf or Webgrind/KCachegrind will show you the functions called, but not their parameters.
You could also use get_defined_functions, which gives you a list of all functions defined. But it won't show you which functions have actually been called, and with what parameters.
If you really need to know the parameters, I don't know of any tools other than a custom logger like the one Henze provided in his answer.

Can I include code into a PHP function or method?

I want to make a kind of "generic" function which gets executed and - depending on what to do - includes it's implementation file via include(). So for example, I might have exactly one function and exactly 20 procedure files for that function. The procedure files may look like do_this_procedure.php, do_that_procedure.php, etc.
As I'm new to PHP I'd like to know from PHP expertes wether this is fine with PHP or not, before I try it and only "believe" it works, and in reality a lot of things go wrong. So what do you think? Currently I think of an include just as an insertion of code right into that place before it gets compiled for execution.
From the include statement documentation:
If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.
So yes, you can call include from within a function and use that to define the body of the function. You can even have the file that you include vary with each call to the function. The downside is the include will be evaluated with each call to the function; if the function is called many times, it could seriously impact performance.
Depending on exactly what you're trying to accomplish, an alternative is to follow a functional programming paradigm, which lets you construct functions at runtime. Before PHP 5.3, it's ugly, so I wouldn't recommend it unless you can require at least PHP 5.3.
You may try this too:
PHP Tokenizer.
//from external script:
<?php
var_dump(token_get_all(file_get_contents('myscript.php')));
?>
Including such file will be done on runtime, I believe. Basically, when PHP hits the include/require function, it will eval that file as an independent one.
I'm not sure whether variables passed to the function will be usable in the included file, but global-ing them should work fine.
#outis hit the nail on the head, but an alternative approach would be to create the function as a static method in a class and create an autoloader (via spl_autoload_register, etc.) to include and call the class method at runtime.
Then again, this really wouldn't really buy you anything unless you're already using an OO approach.
outis is correct, however this strikes me as a very ugly and messy way to implement the code. Why not just have different files with different declarations of a function including the function declaration.
Functions should be as short as possible - as a general rule of thumb I will go back and see if it is practical to refactor any function longer than 20 lines. Bearing this in mind, where's the benefit in including the body of a function from a seperate file?
C.

Categories