简体   繁体   中英

How to use external functions in php?

I'm making several webpage which uses a single function in php a lot. I'm wondering how I can put this function in an external file and use it (I tried include, but it seems like it doesn't work that way), like putting all javascript in one file and put it in the header. Thanks

For PHP code:

//include($_SERVER['DOCUMENT_ROOT'] . "/path/to/myfunction.inc.php"); preferably:
require_once($_SERVER['DOCUMENT_ROOT'] . "/path/to/myfunction.inc.php");

For JS code:

<head>
<script src="/path/to/script.js" type="text/javascript"></script>
</head>

These work if you have the paths set correctly.

If you are using classes, here is a way to include these very easy:

$includePath = dirname(__FILE__);
set_include_path( get_include_path() . ';' . $includePath );
spl_autoload_extensions( '.cls.php' );
spl_autoload_register();

So, to summarize comment-solving:

  1. every php code should start with <?php , even if the files are included, because otherwise PHP assumes it's raw content (goes into HTML mode so to say).
  2. Filenames must be given as quoted strings, not as literally in the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM