Support » Requests and Feedback » 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]

Viewing 3 replies - 1 through 3 (of 3 total)
  • One thought is that it makes your template more code intensive and in order to build or customize your template, you would have to know code fairly well. Creating syntactically correct PHP, for the average user (even someone with a little knowledge of code) can be daunting.
    Peace.

    Agreed… the super nice thing about having the functions print stuff directly makes it MUCH easier for templating for the average user (ie having to just do <?php list_cats() ?> is less confusing than having to do <?php print list_cats()?>

    A method to do it both ways would be nice. The current php-light set of functions but some documented functions for those who want to go further.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘PHP: Return, not print content’ is closed to new replies.