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.
Related
I'm new to PHP, so for example if I have a parent file that include the 2 child files:
include_once('includes/child1.php');
include_once('includes/child2.php');
If child2.php have a class Test with a function test_function:
class Test
{
static function test_function() {
}
}
then can we access this test_function in child1.php like this?
public static function initialize() {
Test::test_function()
}
and if it can, why does it not produce an error since child1.php is included before child2.php(note: I'm coming from Javascript perspective)
No code in child1 or child2 is actually being called. You're just defining some classes and functions, but nothing is calling any of these functions. Test::test_function() is never ever being evaluated, hence it cannot throw any error.
In general: yes, order matters. Everything you're trying to call needs to be defined before you call it. In this case, you're not calling anything, hence it's irrelevant.
Each file should take care of its own dependencies. I.e., child1.php should include (or better: require) child2.php itself if its code depends on it. Don't put the burden of including dependencies on the eventual user of child1.php, this just makes things extremely complicated.
In fact, you should be using autoloading, which will include all necessary files just in time as needed without you having to worry about the complexities of multiple include statements.
You can think of the include family ( include_once, require, require_once ) as a cut and paste type operation. If you follow just envision php creating one big file, pasting the content from each include call ( in the top down order of execution ).
So you might have
index.php
includes.php
functions.php
And if you do this in index
include 'includes.php'
some_function();
And then in includes.php
include 'functions.php'
And then in functions php you have a function some_function(){} you can use this in the index file after the include, php will see it like this
include 'includes.php'
include 'functions.php'
some_function(){}
some_function();
In your example above you would not be able to call the class because you are calling it before including it. Like this
//include_once('includes/child1.php');
Test::test_function();
//include_once('includes/child2.php');
class Test
{
static function test_function() {
}
}
However that said I notice you defined a "method" around your call to Test::test_function() that method would need to be wrapped in a class to work, if that was the intended way then it depends when you instantiate that class, you must do that after the Test class is defined. So for that case we will assume that that method is in a class
class Test2{
public static function initialize() {
Test::test_function()
}
}
Now if you use this class back inside of the parent file or anywhere after the include of child2.php then it will work, so in the parent file if you do this.
include_once('includes/child1.php');
include_once('includes/child2.php');
Test2::initialize();
You would think of this as a big file like this
class Test2{
public static function initialize() {
Test::test_function()
}
}
class Test
{
static function test_function() {
}
}
Test2::initialize();
It should be fine. You just cant call it before it is defined. Make sense?
All that said, I would strongly suggest looking into a PSR autoloader, that is the standard way of including classes these days.
Here is a good post on the topic
http://www.sitepoint.com/autoloading-and-the-psr-0-standard/
Update explination
I'll try to make this as simple as I can. The way PHP works is it loads a file and parses the code, this basically means it just checks the formatting for syntax errors or typos and any new functions or class definitions ( it only registers the names of that new stuff and checks the syntax ). Once that is done and passes it starts to execute the code from top to bottom.
Now when including a file it can't parse it right away because it needs to execute the includes, which it does not do during the initial parsing. After it runs the include it parses the new chunk of code, and then continues executing that new code from top to bottom until the end of the included file at which point it returns to the original file and continues on from the include deceleration.
So while it seems different that you can run a function before defining it in the same file, but not in an included file, it is actually the same behavior. This is because it needs to execute the file to know the functions or code that is in it. So if you call the function before the include, PHP hasn't had a chance to even look in the file yet. Some of this is because you could put an include in an if statement and then PHP would not need to include the file.
What it doesn't do is, parse the file run all the includes and then run the code. I hope that clarified how the process flow works.
Where is it wisest to include files in a PHP class file? For example if one of the methods needs a external class, should I include the file where it is used in that method, or should it be done before the class? Or in the constructor? Or? What do you recommend? Pros? Cons? Or is it just a matter of taste really?
include_once 'bar.class.php';
class Foo
{
public static function DoIt()
{
new Bar();
}
}
vs
class Foo
{
public static function DoIt()
{
include_once 'bar.class.php';
new Bar();
}
}
I prefer it on top, the same convention as for #import/import/using in c/java/c# as it immediately lets you know what other classes your class is depending on.
You may also want to check out require_once() instead of include_once() as it will halt with an error instead of giving a warning when the included file contains an error. But of course that depends on what kind of file you're including and how critical you deem it to be.
I would say that it depends.
So, if there is a rather large code base, and you would prefer to keep the code loaded into memory each time there is a page request down to a minimum, then I would suggest only including the other php file when needed.
However, if that script is always needed, then include it at the top of the script.
It really comes down to the situation and requirements.
Hope that helps.
It depends on architecture you are using. Including files in the beginning is neat, but if that file prints text then you wont be able to manipulate headers etc.
When you are using MVC pattern controller should include class files.
If you're sure you need the file included, do it at the top. If you need files included on demand, you might want to look into spl_autoload_register() to ease the pain.
It is always good to include external files on top of the page. It will be very easy to locate later. If the included file is very large then include it wherever you need. See also the documentation for require_once and include_once.
There's also simply require and include. Know the difference between them and which to use when.
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.
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.
I am needing some information on including files in PHP classes. E.G.
include Foo2.php; //<--- Is this good?
class Foo {
function doFoo(){
include("Foo2.php"); //<--- or is this better?
//do something with vars from Foo2
}
}
I was wondering what the differences were beside scope and if there were any other ways to include another php file in a class.
Thanks in advance for any responses.
include at the global scope. It's much readable and maintainable.
You can only include PHP files in the functions of a class, or outside the class completely, so you have both of the ways down.
The difference of those is that the one inside the function will only be included if you call that function.
I find that the one inside of the function is better, because then it won't be included automatically, and you can only include it if you need a function inside that class, which can be really helpful if you deal with a LOT of files.