PHP: Return, not print content
-
This is obviously not something that can be done overnight, but I would like to propose the following:
Instead of the PHP functions printing out the results of the queries and operations they perform, they should return the content as variables and/or arrays. So instead of:
function foo($a) {
$i = $a+1;
print $i;
}
You would have
function foo($a) {
$i = $a+1;
return $i;
}
In the page template you would then do:
<?php
print foo(3);
?>
At first glance this might not seem to make much of a difference, but there are two main reasons I am suggesting this:
1. The functions can complete their operations before outputting any data, which avoids invalid markup or other errors in case the function fails half way through.
2.From a user standpoint, the biggest advantage would be to perform operations on the data that’s returned from the function, and not having to hack the WP files in order to tweak the functionality.
As a very basic example, you could have a function like this in the WP code:
function doSomething($myvariable) {
$result = '' . $myvariable . '';
return $result;
}
If I decide that I don’t want the tags that would normally be printed by the function, I could do something like this in my template:
<?php
$data = doSomething('Some text');
$data = ereg_replace('', '', $data);
$data = ereg_replace('', '
', $data);
print $data;
?>
Which would result in <pre>Some text
</pre> printed on my page. A very crude example, but hopefully you get the idea.
I hope I’ve explained my request in a clear enough manner, and that you excuse any typos or wrong syntax.
[Edited to fix some encoding issues]
- The topic ‘PHP: Return, not print content’ is closed to new replies.