简体   繁体   中英

Do you prefer functioning or including within one php file?

How do you manage your php codes? Do you prefer functioning within one php file or including larger blocks of "raw code"?

Edit: In fact, my code is pretty nasty, as I don't use any namespaces and classes - only functions and including. I shall look the classes up ^^.

Use them as you need them. I use include for chunks of big code doing processing, and functions for "utility" functions. Sometines i use includes within function also... it really depends on how clean you like your code.

Think that many includes means more fopen() from the PHP module, and those can slow doewn the whole script execution..so dont try and put too many includes though.

If you are using php classes, this will sort itself out. If you are not, then it's really hard to give an acceptable answer, except that you should learn to. All php code I've seen done either way without classes seems to become quickly messy.

I agree that OOP is the way to go. Large solid blocks of code are nightmare for maintenance. Definately not the way to go. You should split your code into small blocks that interact with each other and are easily maintanable on their own.

当我以前用PHP编程时,我喜欢将通用工具功能分组在一个公共文件中以包含在大多数页面中,并把类分组在专用文件中,以便仅在需要时加载它们。

I typically use functions/classes for logic and includes for display. I end up with something like this in a controller...

case 'widgetlist':
  $widgets = $DAO->getWidgets();   //get some query
  include('view/showWidgets.php'); //assume a global $widgets variable
  break;

I have found it easier to give an HTML/CSS designer an include rather than a function call which displays. The down side is that I rely on globals to pass variables to the include rather than arguments which are much safer.

I make classes in separate files, with the correct prefixes as namespace (until they are included at least). I also put functions as static methods in "static classes" for the namespace effect.

I use autoload to include the files so I don't have to write a hundred includes. Save My_Example_Class as {lib}/My/Example/Class.php

The thing I'm working on has one included file at the top of every page that contains all the global functions and database setup stuff. It works as-is but I'm now moving the functions into separate files, because with everything in a big lump it's completely impractical to do any testing.

PHP has an __autoLoad () magic function that you can use to intercept class calls. If the class doesn't exist yet, you can setup some simple code to go and look for the proper class code to include. It will then continue to execute as normal.

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