why can't you use print () in module function?

bjraines - July 20, 2008 - 01:03

I didn't realize until now that you could not use print ('Hello') but had to use return t('Hello');

Can someone tell me why this is?

I am just curious

It makes complete sense if you think about what happens

styro - July 20, 2008 - 02:35

What exactly would you expect print() to do? Actually, more specifically WHEN would you expect print() to print something? And WHERE would you expect print() to print something? What then would the theme then do with it afterwards?

These are all very uncertain during the page creation process. How would you control when and where your print() actually outputs? Especially if it is getting run before the theme engine has even kicked in which is the case in a module.

The reason you can use print() in theme templates is because they are 'eval'led by the PHP intepreter as a PHP file and are the last stage in generating the HTML output when Drupal is assembling and nesting all the bits into their correct output order. Drupal assembles the output from modules before running it through the theme engine - being that modules are just a collection of functions, the return statement seems to be the obvious way for a module to send something back to Drupal when it asks for it.

PHP output is just a string of HTML text that gets sent to the browser - Modules mostly run before the theme engine processes page.tpl.php, so using print() in a module would presumably just output some text before the opening <html> tag (ie from the page.tpl.php file) gets sent to the browser which isn't valid HTML.

--
Anton
New to Drupal? | Troubleshooting FAQ
Example knowledge base built with Drupal

Actually, you *can* use

coreyp_1 - July 20, 2008 - 06:27

Actually, you *can* use print(), but only under specific circumstances.

As previously mentioned, print() in a module is tricky, because it could happen at any time, so in order to make everything appear where it should in your theme, we use "return" statements instead.

However, there are times when you *do not* want your output themed. If that is your intention, then it would be perfectly acceptable to use print() statements, because you are bypassing normal theme operations. There are many situations in which this would be desirable, such as CSV output, feed-like output, or any other non-text output. I used a similar approach to create keyboard graphics in my site (http://www.evangelisticpiano.com). Look at the keyboard parser in the upper right hand corner, and submit the name of a chord (ex. "Csus" or "Ebmin-5/Gb"). The keyboard is a custom module that interprets the form request and dynamically creates a graphic (jpg, if memory serves). Obviously, I wouldn't want *that* passing through the theme system!

Hope that clarifies some things...

- Corey

 
 

Drupal is a registered trademark of Dries Buytaert.