php学习笔记8-(定义函数)

本文探讨了PHP中关于变量作用域的特殊规则,包括全局变量在函数中的使用限制及如何通过global关键字来解决。此外,还介绍了PHP函数定义的特点,如参数类型的灵活性以及默认参数值的设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作用域比较奇怪,一般的全局变量是不能在函数中使用的,不过代码块对作用域没有影响。 另外,参数定义时不能指定类型,除非它是个对象;返回值也不能指定(array似乎是可以的)。
P.S. 函数名称不区分大小写,而变量名称区分大小写。

head.inc(扩展名是任意的):
<?php
    
# function name does not case sensitive, but variable name does
    // function plus(integer $a, integer $b) {  <-- WRONG!!!
    //                     here integer should be a class

    function plus($a,$b) {  
        
return $a+$b;
    }
    
    
function mul($a, $b) {
        
return $a*$b;
    }
?>

func.php:
#!/usr/bin/php
<?php
    
// if head.inc was not be found, require() will cause a fatal error, but include() will
    // cause a warning
    // use require_once/include_once to avoid from include a file more than one time

    require_once('head.inc');
    
    
echo plus(3,4)." ";
    
echo mul(3,4)." ";
    
echo "------- ";

    
# scope
    # P.S. code block {} does nothing about scope
    $x=3;
    
function a() {
        
echo $x." ";  // $x is a global variable, 
        // but it non-visible here 
        // except $x is a super global variable

    }
    a();
    
echo $x." ";

    
# make a variable to be global
    function b() {
        
global $y;  // export $y to be global
        $y=4;       // assigned after global declaration
        echo "$y ";
    }
    b();
    
echo "$y ";

    
# default value
    function c($z=5) {
        
echo "$z ";
    }
    c();
    c(
6);
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值