Php include at runtime

How to use include within a function?

I have a large function that I wish to load only when it is needed. So I assume using include is the way to go. But I need several support functions as well -only used in go_do_it(). If they are in the included file I get a redeclare error. See example A If I place the support functions in an include_once it works fine, see Example B. If I use include_once for the func_1 code, the second call fails. I am confused as to why include_once causes the function to fail on the second call, it seems to not ‘see’ the code the second time but if nested functions are present, it does ‘see’ them. Example A:

 ?> Doing it'; nested_func() function nested_func() < echo ' in nest'; >?> 

3 Answers 3

The problem with using include() within a function is that:

include 'file1.php'; function include2()

file1.php will have global scope. file2.php ‘s scope is local to the function include2 .

Now all functions are global in scope but variables are not. I’m not surprised this messes with include_once . If you really want to go this way—and honestly I wouldn’t—you may need to borrow an old C/C++ preprocessor trick:

If you want to go the way of lazy loading (which by the way can have opcode cache issues) use autoloading instead.

I have a large function that I wish to load only when it is needed. So I assume using include is the way to go.

Your base assumption is wrong. This kind of optimization is counter-productive; even if your function is hundreds of lines long there will be no noticeable benefit to hiding it from PHP’s parser. The cost for PHP to parse a file is negligible; real noticeable speed gains come from finding better algorithms or from better ways to talk to your database.

Читайте также:  Градации серого цвета html

That said, you should be including the function definition in the included file. Rather than moving the body of the function into func_1.php , move the entire function into the file. You can then require_once the file containing the function inside each file where you need it, and be sure that it is included exactly once regardless of how many times you attempt to include it.

file1.php

index.php

require_once('file1.php'); include('table_of_contents.php'); test(); 

Источник

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)

4 Answers 4

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?):

 //doThing(); echo "Done testing."; 

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)

Encapsulate myBigFunction() in a class

save it as myBigFunction.php

When you call the function as static method on the class :

__autoload will load the file, but not before that.

This is definitely the way to go. Splitting functions into individual files will cause a lot of extra confusion, and the many small files may actually make it less performant. Grouping functions into meaningful classes, on the other hand, helps you organise your code and maintain it as it grows.

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.

Yes, I know it is possible. My question is about optimization. Would be better to write an include inside a function in order to make it smaller? (Having functions that are quite big and they are loading every time the page is loaded). Thank you.

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.

Источник

How to achieve «compile-time includes» in PHP?

If bootstrap.php does not exist, we get a runtime exception, e.g. «500 Internal Server Error». How can we include bootstrap.php into page1.php such that they are treated as one unit instead of two separate units mungled together at run-time? Is there any way to achieve «compile time» includes in PHP?

It looks like you are trying to tackle this problem the wrong way. Can’t you just require the file in the bootstrap file of your project? Otherwise I think you may want to look into a custom error handler.

A bootstrap file is a file which always loaded as the first thing in your file chain. This can then be used to load required script and-or setup the run environment. Basically all requests get routed through this file and after that it decides what other files to load next.

@PeeHaa, Yes, we’re both talking about this «bootstrap file». There’s no guarantee that this bootstrap file exists on the file system. The question is asking how can we sorta «compile time» include this bootstrap file?

People are already encouraged to post comments on downvotes. And people not commenting on downvotes might just have a good reason for not doing hence the reason it is not mandatory. So imho asking for comments on downvotes just introduces noise.

3 Answers 3

This is wrong assumption of yours.

Neither 200 nor 404 have to be sent in case of error but 503.

It is said that modern PHP versions have to take care of it, but I have some reports that it doesn’t.
The only guaranteed way known to me is to use php-fpm, as sending 503 in case of error is one its core features.

Anyway, at least try to set display_errors = off in PHP settings (ini or perdir) and see. there should be no error message (as it ought to be on a live server) but 5xx status which will tell a client that page exists but experience temporary problems.

Ok it is debatable whether we should return 404 or 503. But this is not the point. How do we emulate «compile time» includes in PHP?

Regarding your edit, I would say I don’t think you understood the question (see above). I do not want to tell the client the page exist. I want to tell the client the page doesn’t exist.

Yep. That’s what you are doing wrong. You may want 404 only if included file contains data, not code. Yet it haven’t to be an include() at all in this latter case.

If you really want to do this, then it would be easier to just invert the problem using URL rewriting. Instead of making main.php and all your other scripts include bootstrap.php, just have a third script include bootstrap.php and the others.

You can keep your existing URLs and use rewrite rules to route all requests to the affected files through this central script. This script would do your include/error check of bootstrap.php and then either send the 404 response or figure out the original script path based on the request URI and include it. That would allow you to do all your custom error handling in one place.

It all depends on what you’re trying to accomplish and why bootstrap.php would be missing. If main.php is the request entry-point, then your options are pretty limited. Another option would be to put your error checks in a file that’s loaded using the auto_prepend_file directive, but then you’d have to guarantee that that file always exists. I’m not sure whether or not that’s an improvement.

(Note: answering my own question as a proper answer had not appeared after several months.)

True compile-time includes does not exist in «native» PHP because the very essence of PHP is an interpreted / runtime scripting language.

PHP accelerators may give the illusion of compile-time includes, but they actually track the state of each included file and redo an include at runtime if the file is edited. Which means that we’ll still get a runtime error/warning if the included file is deleted, or if it doesn’t even exist in the first place.

However, what’s wanted can be accomplished using a PHP preprocessor which replaces all your include statements with their actual file content. This will work as long as the name of the included files are not dynamic strings and can be statically determined. (It’s not too tough to write a custom preprocessor if your use cases are simple — e.g. no usage of namespaces etc).

If all that’s wanted is to return a 404 page when an include statement fails, then look for an option provided by the web server. If it doesn’t allow such a configuration, the only fall back would be URL rewriting solution as provided by Peter’s answer.

Источник

Оцените статью