在PHP中使用函数vs include作为"子例程"

IMB*_*IMB 2 php function subroutine

推荐的方法是哪种?

使用包括:

// subroutine.php

echo 'hello '.$a;

// usage.php

$a = 'foo';
include 'subroutine.php';
Run Code Online (Sandbox Code Playgroud)

使用功能:

// subroutine.php

function subroutine ($a)
{
    echo 'hello '.$a
}
Run Code Online (Sandbox Code Playgroud)

// usage.php

include 'subroutine.php';
$a = 'foo';
subroutine($a);
Run Code Online (Sandbox Code Playgroud)

因为在技术上工作,因为PHP中没有"子程序",例如ASP.模拟子程序的最佳方法是什么?

xbo*_*nez 5

功能更适合此目的.包含更广泛地用于模板,或者当控制器调用视图时.

但是,您的函数不应该回显连接的字符串.它应该归还它.

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

function subroutine($a) { return "hello " . $a; }
Run Code Online (Sandbox Code Playgroud)

这使您的代码可以测试.