Using require_once inside a method - php

From what I understand using something like require_once will essentially copy and paste the code from one file into another, as if it was in the first file originally.
Meaning if I was to do something like this it would be valid
foo.php
<?php
require_once("bar.php");
?>
bar.php
<?php
print "Hello World!"
?>
running php foo.php will just output "Hello World!"
Now my question is, if I include require_once inside a method, will the file that is included be loaded when the script is loaded, or only when the method is called?.
And if it is only when the method is called, is there any benefit performance wise. Or would it be the same as if I had kept all the code into one big file.
I'm mainly asking as I've created an API file, which handles a large amount of calls, and I wan't to simplify the file. (I know I can do this just be creating separate classes, but I thought this would be good to know)
(Sorry if this has already been asked, I wasn't sure what to search for)

It will only include when the method is called, but have you looked at autoloading?

1) Only when the method is called.
2) I would imagine there's an intangible benefit to loading on the fly so the PHP interpreter doesn't have to parse extra code if it's not being used.

I usually use the include('bar.php'); i use it for when i use databvase information, i have a file called database.php with login info and when the file loads it calls it right up. I don't need to call up the function. It may not be the most effective and efficient but it works for me. You can also use include_once... include basically does what you want it to, it copies the code essencially..

As others have mentioned, yes, it's included just-in-time.
However, watch out for variable definitions (require()ing from a method will only allow access to local variables in that method's scope).
Keep in mind you can also return values (i.e. strings) from the included file, as well as buffer output with ob_start() etc.

Related

how to include a php file that already includes another file?

I am trying to include 2 php file in two separate <td> tags in the same table.
<td><?php include 'login.php';?> </td>
<td><?php include 'register.php';?> </td>
Both the php files include another php file for connecting to a database (eg. <?php include 'database.php';?>
Now, the problem is, the second file doesn't show up in the table. First file works.
Php files work independently. No problem with the code.
I removed the include in 1.php and everything worked fine - ie. both the files show up in table.
My conclusion is, it goes on including indefinitely. Now, how do I solve this?
regards
Ganesh Kumar
You can use include-once
The include_once statement includes and evaluates the specified file
during the execution of the script. This is a behavior similar to the
include statement, with the only difference being that if the code
from a file has already been included, it will not be included again.
As the name suggests, it will be included just once.
i.e.:
include_once('database.php');
include_once('login.php');
include_once('register.php');
You actually have several options, now that I think about it.
Require_once:
require_once('database.php')
This is the most accepted method for files such as this one that you describe, as it will hard-fail if the file cannot be included. For files that do program instantiation (I.e. database connection) this method is preferred.
Include_once:
include_once('login.php')
I've never found a reason to use this statement over require_once; however, that said, it doesn't mean there isn't one. If you have a file that does some instantiation of something related to your programme that isn't mission-critical, then you could suppose to use this directive over the other.
Define Include Constants:
This method requires a bit more explanation: instead of starting your included file (database.php in our example) off with the code for it, start it off in a manner similar to C/C99/C++.
<?php
if (!defined("INCLUDED_DATABASE"))
{
define("INCLUDED_DATABASE", true);
// add main body of file here
}
?>
This method basically accomplishes the same thing as the include_once and require_once, except that in no circumstances will it ever actually process the body twice in one request, even if you forget to use _once as a suffice to your include/require method. This goes back to the old days of C/C99/C++
where including a file twice would hard-fail the compiler, as duplicate definitions would take place.
Personally, I have always preferred the last option: it's the most strict. Yes, require_once and include_once when used diligently will have the same effect, but suppose someone (not even you necessarily) is modifying the application and accidentally does an include or require without the _once suffix, they will be having a bad day. This method prevents that.
That said, I still use a require_once when necessary, and a require if it can be included multiple times. (Files with that designation are not designed with the define construct.)

How to know if a script was included inside another script

I am new to PHP and very likely I am using the incorrect approach because I am not used to think like a PHP programmer.
I have some files that include other files as dependencies, these files need to have global code that will be executed if $_POST contains certain values, something like this
if (isset($_POST["SomeValue"]))
{
/* code goes here */
}
All the files will contain this code section, each one it's own code of course.
The problem is that since the files can be included in another one of these files, then the code section I describe is executed in every included file, even when I post trhough AJAX and explicitly use the URL of the script I want to POST to.
I tried using the $_SERVER array to try and guess which script was used for the post request, and even though it worked because it was the right script, it was the same script for every included file.
Question is:
Is there a way to know if the file was included into another file so I can test for that and skip the code that only execute if $_POST contains the required values?
Note: The files are generated using a python script which itself uses a c library that scans a database for it's tables and constraints, the c library is mine as well as the python script, they work very well and if there is a fix for a single file, obviously it only needs to be performed to the python script.
I tell the reader (potential answerer) about this because I think it makes it clear that I don't need a solution that works over the already existant files, because they can be re-generated.
From the sounds of it you could make some improvements on your code structure to completely avoid this problem. However, with the information given a simple flag variable should do the trick:
if (!isset($postCodeExecuted) && isset($_POST["SomeValue"]))
{
/* code goes here */
$postCodeExecuted = true;
}
This variable will be set in the global namespace and therefore it will be available from everywhere.
I solved the problem by doing this
$caller = str_replace($_SERVER["DOCUMENT_ROOT"], "", __FILE__);
if ($_SERVER["REQUEST_METHOD"] === "POST" and $caller === $_SERVER["PHP_SELF"])
performThisAction();

Suppress echo from PHP include file

I have a file PHP01.php which:
- performs a function
- creates an array
- echo's some message
I need to include this file in another php script, say PHP02.php as I need access to the array it created. But when I jquery POST request to PHP02.php, the data it returns also has the echo from PHP01.php
How can I suppress the echo from the first file?
You can output buffer it if editing or otherwise restructuring is not possible:
ob_start();
include "PHP02.php";
ob_end_clean();
If you can, you should look at refactoring the code in the original PHP file. If it's performing a function, it should do that. Then, the code that called the function should decide if they want to echo a message.
As you've just learned, this is an important part of orthogonal design. I'd recommend re-writing it so that it performs what you want it to, and let the code that calls the function, decide what they want to output. That way you won't have to worry about these things again.
You can also look into using output buffers. See ob_flush in PHP: http://php.net/manual/en/function.ob-flush.php
Try adding a conditional to PHP01.php that checks to see where it is being called from, this will ensure that you only echo it out if the file making the call is PHP01.php
Additionally it is better if you place functions in their own file to be included if needed so as to keep certain features that are present from being included for example in PHP01.php you can add include 'function01.php'; and it will have that function shared across the two files.
create a new function without the echo

How can I reference variables from another included file in PHP?

So I'm working on a PHP app and trying to make everything moduler. I have an index.php file that includes other php files. The first file included is settings.php which has my postgres credentials defined so they can be accessed elsewhere. The second file is connect.php that has a function you can pass sql to and it will return $result. The third file has functions that call the sql function and receive $result and parse it. In the third file, I can read the results of the $result however if I try if($result) it breaks and isset/empty have no effect.
Anyone have any ideas on a way to make this work, or is my structure just terrible?
Thanks so much!
Mike
let's say you have the following three files:
inc1.php
<?php
$foo = 'hello';
?>
inc2.php
<?php
echo $foo;
?>
main.php
include('inc1.php');
include('inc2.php');
it should echo "hello". however, passing variables around among files is a bad idea, and can lead to a lot of confusing, hard-to-follow code. If you need to pass variables around, use functions and/or objects so that you can at least see where they are coming from.
beyond that though, it's difficult to tell exactly what your problem is without seeing the code in question.
I would really try to switch to OOP. This makes things a lot of easier. If you just have to deal with classes, their methods and attributes you only have to include the classes and not this choas of functions. So I would recommend, give it a go ...

How to setup site-wide variables in php?

I want to define something like this in php:
$EL = "\n<br />\n";
and then use that variable as an "endline" marker all over my site, like this:
echo "Blah blah blah{$EL}";
How do I define $EL once (in only 1 file), include it on every page on my site, and not have to reference it using the (strangely backwards) global $EL; statement in every page function?
Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that first line of code in the header file, then include it like this on every page:
include 'header.php';
you won't have to use the global keyword or anything, the second line of code you wrote should work.
Edit: Oh sorry, that won't work inside functions... now I see your problem.
Edit #2: Ok, take my original advice with the header, but use a define() rather than a variable. Those work inside functions after being included.
Sounds like the job of a constant. See the function define().
Do this
define ('el','\n\<\br/>\n');
save it as el.php
then you can include any files you want to use, i.e
echo 'something'.el; // note I just add el at end of line or in front
Hope this help
NOTE please remove the '\' after < br since I had to put it in or it wont show br tag on the answer...
Are you using PHP5? If you define the __autoload() function and use a class with some constants, you can call them where you need them. The only aggravating thing about this is that you have to type something a little longer, like
MyClass::MY_CONST
The benefit is that if you ever decide to change the way that you handle new lines, you only have to change it in one place.
Of course, a possible negative is that you're calling including an extra function (__autoload()), running that function (when you reference the class), which then loads another file (your class file). That might be more overhead than it's worth.
If I may offer a suggestion, it would be avoiding this sort of echoing that requires echoing tags (like <br />). If you could set up something a little more template-esque, you could handle the nl's without having to explicitly type them. So instead of
echo "Blah Blah Blah\n<br />\n";
try:
<?php
if($condition) {
?>
<p>Blah blah blah
<br />
</p>
<?php
}
?>
It just seems to me like calling up classes or including variables within functions as well as out is a lot of work that doesn't need to be done, and, if at all possible, those sorts of situations are best avoided.
#svec yes this will, you just have to include the file inside the function also. This is how most of my software works.
function myFunc()
{
require 'config.php';
//Variables from config are available now.
}
Another option is to use an object with public static properties. I used to use $GLOBALS but most editors don't auto complete $GLOBALS. Also, un-instantiated classes are available everywhere (because you can instatiate everywhere without telling PHP you are going to use the class). Example:
<?php
class SITE {
public static $el;
}
SITE::$el = "\n<br />\n";
function Test() {
echo SITE::$el;
}
Test();
?>
This will output <br />
This is also easier to deal with than costants as you can put any type of value within the property (array, string, int, etc) whereas constants cannot contain arrays.
This was suggested to my by a user on the PhpEd forums.
svec, use a PHP framework. Just any - there's plenty of them out there.
This is the right way to do it. With framework you have single entry
point for your application, so defining site-wide variables is easy and
natural. Also you don't need to care about including header files nor
checking if user is logged in on every page - decent framework will do
it for you.
See:
Zend framework
CakePHP
Symfony
Kohana
Invest some time in learning one of them and it will pay back very soon.
You can use the auto_prepend_file directive to pre parse a file. Add the directive to your configuration, and point it to a file in your include path. In that file add your constants, global variables, functions or whatever you like.
So if your prepend file contains:
<?php
define('FOO', 'badger');
In another Php file you could access the constant:
echo 'this is my '. FOO;
You might consider using a framework to achieve this. Better still you can use
Include 'functions.php';
require('functions');
Doing OOP is another alternative
IIRC a common solution is a plain file that contains your declarations, that you include in every source file, something like 'constants.inc.php'. There you can define a bunch of application-wide variables that are then imported in every file.
Still, you have to provide the include directive in every single source file you use. I even saw some projects using this technique to provide localizations for several languages. I'd prefer the gettext way, but maybe this variant is easier to work with for the average user.
edit For your problem I recomment the use of $GLOBALS[], see Example #2 for details.
If that's still not applicable, I'd try to digg down PHP5 objects and create a static Singleton that provides needed static constants (http://www.developer.com/lang/php/article.php/3345121)
Sessions are going to be your best bet, if the data is user specific, else just use a conifg file.
config.php:
<?php
$EL = "\n<br />\n";
?>
Then on each page add
require 'config.php'
the you will be able to access $EL on that page.

Categories