Home > Backend Development > PHP Tutorial > PHP code reuse and functions

PHP code reuse and functions

WBOY
Release: 2016-07-29 09:15:33
Original
1095 people have browsed it
<?php
//使用require()、include()函数
echo &#39;This is the main file.<br/>';
require('reusable.php');
echo 'The script will end now.<br/>';
//函数声明
function my_function(){
    echo 'My function was called';
}
my_function();
//使用参数
function create_table($data){
    echo "<table border=\"1\">";
    reset($data);
    $value=current($data);
    while($value){
        echo "<tr><td>".$value."</td></tr>\n";
        $value=next($data);
    }
    echo "</table>";
}
$my_array=array('Line one','Line two','Line three');
create_table($my_array);
//作用域 关键字global
function fn(){
    global $var;
    $var="contens 2";
    echo "inside the function,\$var =".$var."<br/>";
}
$var="contents 1";
fn();
echo "outside the function,\$var =".$var."<br/>";
//参数的引用传递和值传递:地址符&
function increment(&$value,$amount=1){
    $value=$value+$amount;
}
$a=10;
echo $a.'<br/>';
increment($a);
echo $a.'<br/>';
//return关键字:终止函数的执行
function larger($x,$y){
    if((!isset($x))||(!isset($y))){
        echo "This function requires two numbers.<br/>";
        return;
    }
    if($x>=$y){
        echo $x."<br/>";
    }else{
        echo $y."<br/>";
    }
}
$a=1;
$b=2.5;
$c=1.9;
larger($a,$b);
larger($d,$a);
//return关键字:从函数返回一个值
function smaller($x,$y){
    if((!isset($x))||(!isset($y))){
        return false;
    }else if($x<=$y){
        return $x;
    }else{
        return $y;
    }
}
echo smaller($a,$b).'<br/>';
echo smaller($d,$a).'<br/>';
//实现递归
function reverse_r($str){
    if(strlen($str)>0){
        reverse_r(substr($str,1));
    }
    echo substr($str,0,1);
    return;
}
function reverse_i($str){
    for($i=1;$i<=strlen($str);$i++){
        echo substr($str,-$i,1);
    }
    return;
}
reverse_r('hello');
echo '<br/>';
reverse_i('hello');
//phpinfo();
Copy after login


更多细节参考php手册—函数

版权声明:本文为博主原创文章,未经博主允许不得转载。

以上就介绍了php的代码重用与函数,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template