tags:

views:

60

answers:

3

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

+3  A: 

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.

Sarfraz
but why? What is the difference between them in performance?
phpExe
@phpExe: Difference between what?
Sarfraz
1. include the script 2. write the script as function in for example functions.php, include the functions.php and call function
phpExe
@phpExe: Both times you include a script. Can you please elaborate more on the differences between the approaches. Repeating them is not helpful, we can all read.
Felix Kling
@phpExe: There is no in difference in performance because you are including in both ways any way. Or rephase your question because it doesn't make much sense.
Sarfraz
@phpExe: you do it to organize your code, if you had them all classes and functions in one file it would be harder to manage
Moak
@Felix Kling, I have a huge file named functions.php. I have included this file in all pages. But I want to know if it is a right way.
phpExe
+2  A: 

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.

Matijs
+2  A: 

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.

Felix Kling