What is the difference between include() and calling a function in PHP?
For example :
1-
<?php
$foo = '<p>bar</p>';
return $foo;
?>
<html><body><?php echo $foo; ?></body></html>
2-insert above php code in a php file and include()
thanks in advance
include() simply takes the full contents of the file and inserts it in, replacing the include() with the contents of the file.
If you have HTML in the included file, it will be output. If you only have PHP in it, the PHP will be run.
To call a function, the function must be available. If the function is in another file, you will still need to include() or require() that file to have it available.
Generally, including is used to get a set of functions or objects into your running script, so that they can be used, although it can also be used as a standalone page or some bit of HTML, like you posted. In reality, it depends on whether you'd rather have another function on the same script or in a remote script, for aesthetics or organization, whatever your reason.
Functions will usually run a bit faster, as server response time and parsing time may make the include function run a bit slower, but for all intents and purposes you wont notice much. Most of the lag will be due to the fact that a local function will be executed with the page, whereas the include function must execute the page, load another page, and then execute that page as well. If that makes sense.
Just as an addition to the existing answers, you can also do this:
sample.php:
<?php
$foo = include('include_with_return_value.php');
?>
<html><body><?php echo $foo; ?></body></html>
and include_with_return_value.php:
<?php
return '<p>bar</p>';
So, include() files can also have a return value, just like functions.
Related
Do functions parse the code when they are called or are they loaded even if the function isn't be called? Sorry if it seems like a newbie question, I'm just curious about this.
Thank you
They do not "process their code" until they are called. For example:
function my_function() {
return "Hello World";
}
The above will not execute until you call it:
echo my_function();
With that said, the code in your function still needs to be valid or it will cause errors.
You may want to read the User-defined functions or W3 Schools PHP Functions.
To keep the script from being executed when the page loads, you can
put it into a function. A function will be executed by a call to the function.
All code in a PHP file is parsed and converted to PHP bytecode before any of it is run.
For instance, a PHP file with a syntax error anywhere in it will fail to run at all, even if the syntax error isn't anywhere near the part that is being run.
I have a php file on my server that takes in two inputs through the URL and then comes back with a result. When a page is loaded, I'd like to have the result of that calculation already loaded. For example:
$var = load("http://mysite.com/myfile.php?&var1=var1&var2=var2");
I know that load isn't a real function for this, but is there something simple that suits what I'm looking for? thanks
Use file_get_contents
$foo = file_get_contents('http://mysite.com/myfile.php?&var1=var1&var2=var2');
Or, a better solution if the file is located on your server:
include('myfile.php');
and either set the $_GET variables in the included script itself, or prior to including it.
If they are running on the same server, consider calling the script directly?
$_GET["var1"] = "var1";
$_GET["var2"] = "var2";
include "myfile.php";
You could use file_get_contents, but it may be a more practical solution to simply include the file and call the function directly in the file, rather than trying to manually load the file.
as we know, return keyword will RETURN some value and exit current function. Mean, that this one used only inside some functions.
BUT, I saw some php-dev's use return keyword outside functions, even in index.php file (in root of web server). What is that mean???? By the way, maybe it's logical to require some file inside function, but this style isnt mine.
There's not much more to say than what the docs do.
About the common usage of return:
If called from within a function, the return statement immediately
ends execution of the current function, and returns its argument as
the value of the function call. return will also end the execution of
an eval() statement or script file.
About the less common usage:
If called from the global scope, then execution of the current script
file is ended. If the current script file was included or required,
then control is passed back to the calling file. Furthermore, if the
current script file was included, then the value given to return will
be returned as the value of the include call. If return is called from
within the main script file, then script execution ends. If the
current script file was named by the auto_prepend_file or
auto_append_file configuration options in php.ini, then that script
file's execution is ended.
Its documented somewhere within the manual
// myFile.php
return array( 'foo' => 'bar');
// somewhere else
$config = include 'myFile.php';
echo $config['foo'];
If you use return in the main scope php will leave the file inclusion and use the value as "return value" of the inclusion (include[_once](), require[_once]()).
BUT, I saw some php-dev's use return keyword outside functions, even
in index.php file (in root of web server). What is that mean???
You know the common purpose. But what you are asking is used to prevent code injection in php include files. Take a look at this post which explains it:
Prevent Code Injection in PHP include files
While discussing Coding Standards it was not long ago I argued against
adding ?> at the end of php files. But miqrogroove pointed to me an
interesting aspect why it actually can make sense to have it and an
additional return statement at the end of each file: That one (merely
the return statement) can prevent an attacker to append payload code
to existing PHP files, for example known include files. The
countermeasurement is pretty easy, just add a return statement at the
end of the file. It will end the include “subroutine”:
Example:
/* all the include file's php code */
return;
?>
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.
How can include a external class in a php file?
example:
//Test.class.php
<?php
class Test{
function print($param){
echo $param;
}
}
?>
//######################################################
//test.php
<?php
include('http://www.test.com/Test.class.php');
$obj = new Test();
echo $obj->print("hola");
?>
The class is on another server. I have enabled the allow_url_include and allow_url_fopen.
Why can't I call the function print?
The remote file must output the php source code, not execute it.
To output the PHP code instead of executing you could simply remove the .php extension from the file.
PS: Are you really, really, really sure you need remote inclusion? It's a BIG security risk!
What you're including from the other server isn't the code behind the PHP but the output from it (if you visit that page in a browser you aren't seeing the PHP code if you view source right?)
You either need to reconfigure the other server not to execute the code but display it (not a good idea if it's in any way shared or needs to execute it's own code), or rename the other file to something that isn't first interpretted (try otherfile.php.txt)
Have a look at the documentation:
(...) If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.
Probably the server, you are trying to get the file from, executes the PHP file and only the result (which is empty) is included. You would have to configure the server in such a way that it outputs the PHP code. But this is not a good idea if it is sensible code.