2

Which is the recommended approach?

Using include:

// subroutine.php

echo 'hello '.$a;

// usage.php

$a = 'foo';
include 'subroutine.php';

Using function:

// subroutine.php

function subroutine ($a)
{
    echo 'hello '.$a
}

// usage.php

include 'subroutine.php';
$a = 'foo';
subroutine($a);

Since both technically work and since there is no "subroutines" in PHP unlike ASP for example. What is the best way to emulate subroutines?

3
  • recommended for what exactly? Nov 16, 2012 at 21:14
  • 1
    That depends on the actual code, output length, frequence of usage. Template includes are still widely used. Short output functions are just as common.
    – mario
    Nov 16, 2012 at 21:14
  • functions of course, cause you can put as much as you want in the functions file and call it one time in the top of the page, and it wont affect the page if non of the functions is called
    – Mohd Moe
    Nov 16, 2012 at 21:15

3 Answers 3

5

A function is better suited for this purpose. Includes are more widely used for templating, or for when the controller calls a view.

However, your function should not echo the concatenated string. It should return it.

$a = "foo";
echo subroutine($a);

function subroutine($a) { return "hello " . $a; }

This makes your code testable.

1

It would depend on context, wouldn't it? The first example would be to prefer if you were doing something similar to MVC, where you include the view into the code. But the second example feels clearer as you can see the function call in the program flow.

In this specific example I would say that option 2 is to prefer as it's clearer what is going on.

However, PHP hasn't got subroutines in the same way as ASP. ASP has functions that return data and subroutines that don't. PHP only has functions, which can act as both. The best is to save all output you need(through function calls and classes) and print it "manually" wherever you need it. So the prefered way to do things in PHP is.

<?php
    function subroutine($var) {
        return 'Hello '.$var;
    }

    $a = 'foo';
    echo subroutine($a);
?>

But as a rule, includes should contain function definitions and called script should have the calls to the functions. As it best describes the program flow when debuging.

0

Depends on the code, but most of the time you create some functions and call the right one :P.

Not the answer you're looking for? Browse other questions tagged or ask your own question.