Can I include code into a PHP function or method? - php

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.

Related

How to include a specific function using require_once() or include() functions in PHP?

How to include a specific function based on requirement from a php file containing various function definitions.
eg. PHP file functions.php contains 3 functions a(), b() and c()
I have to use require_once('/f/functions.php') in other.php file to use function c.
What could i do to only include the function c in file other.php file using require_once() function and avoid other functions not to be included ?
There is no built in way to do it. Although there are ways to go around it if you do it for the sport.
While this is highly not recommended. Really, just dont do it... here's how:
1) Read the file as text.
2) find the function block and extract it
3) run it through eval.
This will cause any global state set up in the file to not be run. Which you may or may not want.
SuperClosure does something similar I believe to serialize closures, which by default php does not support.
One could leverage the PHP7 abstract syntax tree to also includes related functions. For example, if there are three functions defined - A, B and C. A uses B internally. If you include A, you would want to also include B.
This wont be more performant than just including the whole file, but feel free to prove me wrong with benchmarks.
You might be interested in namespaces. Both classes and functions support it.
You cannot, period. PHP doesn't have any sort of module system. To "include functions", all you can do is execute a source code file (what include will do), which will by the act of executing the code in the file define those additional functions, or anything else that's in the file. You cannot selectively pick only certain parts of the code to run.

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.

Where to place include statements in a PHP class file

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.

Does including classes that you don't use have impact on performance?

like
require "class.a.php";
require "class.b.php";
require "class.c.php";
class main{
function main(){
if(condition_is_met(){
$this->something = new A();
}else{
$this->something = new B();
}
}
}
Should the files be included in the condition check with require_once, and not all the time?
The question is not clear. In the current code, I think all of the file(s) will get included, whether you use (declare variable of these classes) them or not. If you wan't to not load the class(es) you will not use, you can use the __autoload() function.
http://php.net/manual/en/language.oop5.autoload.php
PHP has to open the file and parse it so it has some impact. For a few files I wouldn't worry about it but it can get out of hand as your files increase. That's why there's autoload, which allows you to load class files only when needed, without having a long list of requires at the top of your files:
http://php.net/manual/en/language.oop5.autoload.php
Also take a look at spl_autoload_register:
http://www.php.net/manual/en/function.spl-autoload-register.php
The only performance it should effect is the time to parse it, but I think that is preferred over complicated include logic hidden midway inside of your file. Not to mention that if you put the require inside of the if statement it is like you inserted that file's text inside of that if statement, which isn't right (and may not work).
Can anyone tell me if you can declare a class inside of a function/if statement?
Anytime you use include or require, PHP is basically copy/pasting the code from the required file into your code. So no matter where you put it, PHP is still opening the file, reading it and dropping it in there, it won't be affected by an if block. In other words, require is parsed before the code is actually run, so yes, you will take a (very small) performance hit even if require is put in an if block and never run. Keep in mind, this is a very small impact. Lastly if you are worried about it, I would use require_once - this ensures that this parsing does not happen twice, for example if a second required file requires the first file, this redundancy won't amount to a second performance hit.

call function defined in a file include after this file

Suppose I have following files
<?php
include 'file_A';
include 'file_B';
?>
a function defined foo() in file_B, is there any way to use it in file_A by any means???
actually, I am working in a application where a range of different functions are defined in modules, I want to use these function across the modules without looking where it defined included before or after the file even.
As PHP is an interpreted language, you cannot do this.
What I would do as a solution is extract the methods you need to share into a CommonMethods class or something similar. Make them static if possible.
Then include the CommonMethods file before file_A and file_B.
I'd spend a little time researching design patterns for PHP before continuing your project. Spaghetti code is never a good thing.

Categories