开发者

Simply include the script or a function?

What is the best way?

  1. include the script
  2. write the script as function 开发者_运维百科in for example functions.php, include the functions.php and call function

thanks


Use the include:

include('functions.php');

Once you have included a file that contains any variables, functions, classes, you can call them normally because now they are part of the script where you have included them.


I still don't understand the differences of your approaches.

But if you have a lot code in this file, indeed, the best way would be to write your code as functions (if you do not already have that) and create several files that contain those.

You should try to categorize your functions and create an own file for each category. Then you have more control over which functions you include and you don't have to include all of them, you just include those files you need the functions from.

For example you can create a file database_util.php that contain database related functions, etc.

In the long run, you should learn about Object Oriented Programming, but don't misuse classes / objects as container of functions. This is not the purpose of OOP and won't help you much.


The decision to either include or use a function is not always a simple one.

In general: if you reuse code in a lot of places you should probably make it a function. Among other reasons a function has it's own variable scope which makes programming neater and more reliable.

If your code occurs only once, is seldom used or when the code to be loaded is not always the same code then including it may be better.

In neither case is the speed of loading an issue. The time difference is in 99.99% of all cases insignificant. The decision whether to use a function or an include should be made on the basis of code organization: what is easier to understand for someone maintaining the code.

In practice you akways use a function or an object to organize your code, unless there is a very compelling reason not to.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜