问:Randy的“构建简单的PHP应用程序”很棒。我从中学到了很多。
关于“函数”部分,我想知道为什么返回一个变量比在函数中回显结果更好?
我试图在下面的示例代码中应用相同的技术。我的代码工作如此处所示,但是当我尝试返回变量而不是回显结果时,它什么也没有输出到屏幕。
任何人都可以在下面阐明或改进我的代码吗?
非常感谢。
<?php
$ products = array();
$ products [“ 1940s-1950s”] = array( “ name” =>“ 1940's -1950's”, “ type” =>“俱乐部问题”,“列表” =>“ 1940s-1950s.htm”, “ section” = >“ 1” ); $ products [“ arsenal”] = array( “ name” =>“ Arsenal”, “ type” =>“ Football Club”, “ listing” =>“ aresenal.htm”, “ section” =>“ 1” ); $ products [“ aldershot”] = array( “ name” =>“ Aldershot”, “ type” =>“ Football Club”, “ listing” =>“ aldershot.htm”, “ section” =>“ 1” ); $ products [“ current_season”] =数组(
“ name” =>“当前季节计划(2014/2015)”,
“ type” =>“”,
“ listing” =>“ 2014-15season.htm”,
“ section” =>“ 2”
);
函数getListView($ products,$ section,$ type){ echo“ <ul>”; foreach($ products as $ product_id => $ product){ if((($ product [“ section”] == $ section)&&($ product [“ type”] == $ type)){{ echo“ <li>” ; 回声'<ahref="?s='。$product_id。'">'; echo($ product [“ name”]); 回声“ <
第1节</ h2 >
< h3 >俱乐部问题</ h3 > <?php getListView($ products,“ 1”,“ Club Issues”)?> < h3 >选定俱乐部</ h3 > <?php getListView($ products ,“ 1”,“ Football Club”)?> < h2 >第2节</ h2 > <?php getListView($ products,“ 2”,“”)?>
答;该代码将起作用
<?php
$ products = array (); $ products [ “ 1940s-1950s” ] =数组(“ name” => “ 1940's -1950's” ,“ type” => “俱乐部问题” ,“列表” => “ 1940s-1950s.htm” ,“ section” = > “ 1” ); $ products [ “阿森纳” ] =数组(“名称” => “阿森纳” ,“类型” => “
“ section” => “ 1”
); $ products [ “ aldershot” ] =数组(“ name” => “ Aldershot” ,“ type” => “ Football Club” ,“ listing” => “ aldershot.htm” ,“ section” => “ 1” );$ products [ “ current_season” ] =数组(“ name” => “ Current Season Programs(2014/2015)” ,“ type” =>
“ section” => “ 2”
); 函数getListView ($ products ,$ section ,$ type ){ $ html = “ <ul>” ; foreach ($ products as $ product_id => $ product ){ if ((($ product [ “ section” ] == $ section )&& ($ product [ “ type” ] == $ type )){ $ html 。= “ < li>“
$ html 。= '<ahref = "?s = ' 。 $product_id 。 '">' ;
$ html 。= ($ product [ “ name” ]); $ html 。= “” </a>,</ li>“ ; } } $ html 。= “” </ ul>“ ; 返回$ html ; } ?>
<h2>第1节</ h2>
<h3>俱乐部问题</ h3> <?php echo getListView ($ products ,“ 1” ,“俱乐部问题” )?>
<h3>选定的俱乐部</ h3>
<?php echo getListView ($ products ,“ 1” ,“ Football Club” ) 吗?>
<h2>第2节</ h2>
<?php echo getListView ($ products ,“ 2” ,“” ) ?>
我能想到的真正原因是关注点分离。您可以使逻辑代码不产生任何具有视图功能的内容,并从视图中以逻辑方式调用该代码,并显示其结果。对于小型应用程序,这不是必需的,这就是为什么要提出要求的原因。您可以看到,如果此站点扩展了,但是如果其中包含一些具有回显功能的函数,而又有一些返回的函数,则可能很难解决。
Wordpress通过功能名称来处理此问题,这是一种选择。例如,the_permalink()将从函数中回显URL。get_the_permalink()只会返回它。您可以通过有意义的函数名称来查看。