call function defined in a file include after this file - php

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.

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.

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.

What is the best practice for including PHP files? [duplicate]

This question already has answers here:
PHP include best practices question
(10 answers)
Closed 9 years ago.
What is the best practice for including PHP files?
Is it best to include a include.php file that includes all of the project PHP files?
Or to include it in those files that need them
Right now, my project has several include files in my index.php file. Does including all of my php files in the index.php make it less efficient?
Lastly, Where should one include the session check PHP file? in all of the PHP files?
EDIT 2016
Well, 5 years since I replied this. I am still alive. A lot has changed.
Now I use autoloaders to include my files. Here is official info for autoloaders with examples.
Basically, the idea is to have a proper folder structure (PSR-4 standards for instance) and having a class within each file. This way you can use autoloaders and PHP will load your files automatically.
OLD ANSWER
Usually, I have a config file like this:
define(root, $_SERVER['DOCUMENT_ROOT']);
.... // other variables that are used a lot
include (root . '/class/database.php');
.... // other includes that are mostly called from each file, like a db class, or user class, functions etc etc...
if (defined('development'))
{
// turn error reporting on
}
else
{
// turn it off
}
etc etc... You got the point of config.
And I include the config.php on each file. I forgot how to do it right now, but apache can do the automatic include for you. Therefore, you can say to apache to include your config file by default.
Then, I have controller classes, which call the views. There in each function I call the view.
someController.php
function index() { include root . '/views/view_index.php'; }
finally, from the view, if I need to include the header and footer view I do it like this:
view_index.php
<?include root . '/view/shared/header.php';?>
<div class="bla bla bla">bla bla bla</div>
<?include root . '/view/shared/footer.php';?>
I always use include in this structure rather than include_once since the latter requires extra check. I mean, since I am pretty sure that I include files only once, I don't need to use include_once. This way, you also know which include is where. For instance, you know that crucial files like db.php, or functions.php are located in config.php. Or you know that include views are located in controllers. That's pretty useful for me, I hope that helps you, too.
Using the include.php file is a very good practice according to me, as it is very helpful in changing the included files in big projects. If the project is small then including individual files is not a problem. But it becomes a problem to manage them as the project grows big.
For the session check file it is better to attach them individually as the requirement to check session on different pages might differ.
Including files individually or including them all in a single file and then including that makes much of the difference to the performance. As ultimately all the files are going to be included. It only becomes easy to manage them if single file is used to handle them.
I don't assume you are using object oriented programming but in case you do here might be a good answer.
In php you can define a function called the autoloader, if you try to create an object of a class that has not been defined the autoloader is called. You can then use the class name to figure out where the file containing that class is stored to include it at the last moment. Here is an example..
<?php
function on_load($class)
{
if(file_exists(require_once('classes/'.$class.'.php')))
{
require_once('classes/'.$class.'.php');
}
else
{
throw new Exception('Class not found: '.$class.' in classes/');
}
}
spl_autoload_register('on_load'); // tell php to call your on_load function if the class was not defined
If you're working on a big project you might want to group your files like this
/classes/database/MySQL.php
/classes/database/PDO.php // I'm just listing random stuff
/classes/Core.php // Whatever
/classes/datastructure/HashMap.php
You can then use a special naming convention to find the right directory
class Database_MySQL{} // look in <root_dir>/database/ for MySQL.php
class Core // look in <root_dir>/ for Core.php
class Database_Driver_Adapter_Useless_MysqlAdapterThingy {} // look in <root_dir>/Database/Driver/... blabla
Or you can use the php 5.3 way and define your classes like this
<?php
namespace database\driver\adapter\useless;
use database\driver\adapter\MysqlAdapter; // Now you have to tell PHP which version of MysqlAdapter class you want to use, even if there is just one
class MysqlAdapterThingy extends MysqlAdapter {}
Now you have to use the 'use' keyword in every file you need that class. The cool thing is that the namespace is automatically added to the class-name for your autoload function so you can do something like this
function on_load($class)
{ require_once('root/' . str_replace('\\', '/' $class)); }
If you want to learn more try googeling PHP auto-loading there is tons of information on this subject. But then again. From the format of you question I do not assume you're using OOP so this answer is just for the people who found this question on google.
Edit
I would also like to add the following:
// Only include the file once even if you place this statement multiple times
require_once('bla.php');
include_once('bla.php');
require('bla.php'); // Error if file doesn't exist, php will not continue
inlcude('bla.php'); // Warning if file doesn't exist, but php will continue
Using include or require without _once means that file will get included every time the statement is executed
Use include for template or user generated files, use require_once for classes
Just think easy, and think about load as less as possible and don't include something unnecessary.
So for your PHP files. if you include same php files on different pages just create 1 PHP file with this files in it.
If you use a PHP file in 1 page or 2 only, just include them seperate.
I hope i helped you with it ;)
Include files independently, use require_once() function instead of include, as require_once allow only one inclusion of file...

Is there something like a macro in PHP? Or: How to make an own include function?

What I want to do is this:
When I write a class and the class instantiates another class, I want to import that class with an require_once. Just the way I do so in Objective-C. But instead of using plain require_once function and messing around with paths and string concatenation, I would prefer something like:
importClass('myclass');
but I'm afraid that it's impossible to write a function that will include code. If I would do that in the importClass() function, I would include the class code into the implementation block of the function, which of course is nonsense. So what options do I have here?
The cleanest way to do what you want looks to be to use the Autoloader
It's not impossible at all. You can write this function:
function importClass($class) {
require_once "$class.class.php";
}
The only caveat is that any global variables declared or used inside that file will now be local to importClass(). Class definitions however will be global.
I'm not sure what this really gives you however but you can certainly do it.
In my application I have a system base class which has a similar function. The import function takes a class name, looks in a couple of related directories and finds a matching name (I also did some stuff with extensions to libraries but you may not need that) and instantiates a class inside with the same name. Then it takes that new instance and sets it as an object in the system base class.
using autoload as other answers have suggested would probably work better in your situation but this is just another way to look at it.
You can accomplish something similar using a class autoloader. I would also make sure that your include_path is set properly and that you are using a directory structure that makes sense for your classes - it's generally a good practice to NOT depend on class autoloaders, and instead include classes based on their relative path to your include_path.
I'd highly recommend browsing through Zend Framework, particularly Zend_Loader, for a good (if not over-architected) implementation. Also notice that Zend Framework will work without an autoloader in place - each file calls require_once on its direct dependencies, using their nice, organized directory structure.

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