PHP经验分享

php简单的代码重用与函数编写

2018-10-06  本文已影响1人  那未明

辨析:

使用PHP函数

  function create_table($data, $header=NULL, $caption=NULL) {
echo '<table>';
if ($caption) {
echo "<caption>$caption</caption>";
}
if ($header) {
echo "<tr><th>$header</th></tr>";
}
reset($data);
$value = current($data);
while ($value) {
echo "<tr><td>$value</td></tr>\n";
$value = next($data);
}
echo '</table>';
}
$my_data = ['First piece of data','Second piece of data','And the third'];
$my_header = 'Data';
$my_caption = 'Data about something';
create_table($my_data, $my_header, $my_caption);
function increment(&$value, $amount = 1) {
$value = $value + $amount;
}

使用return关键字

递归实现

匿名(闭包函数)实现

bool array_walk(array arr,callable func[,mixed userdata])

closures.php —Using a Variable from the Global Scope Inside a Closure
<?php
$printer = function($value){ echo "$value <br/>"; };
$products = [ 'Tires' => 100,
'Oil' => 10,
'Spark Plugs' => 4 ];
$markup = 0.20;
$apply = function(&$val) use ($markup) {
$val = $val * (1+$markup);
};
array_walk($products, $apply);
array_walk($products, $printer);
?>
上一篇 下一篇

猜你喜欢

热点阅读