开发者

What is the difference between include() and calling a function in PHP?

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开发者_JS百科></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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜