php初级讲义9-函数

函数的概念

函数是对一组操作的封装。

自定义函数

自定义函数是用户根据需求自己封装的一组操作。

function get_my_name($name){
    return 'my name is '.$name;
}
echo get_my_name('lilei'); // my name is lilei
echo '<br/>';

ini_set('display_errors', 'on');
error_reporting(E_ALL);

/*function 1_get_number($i){ // 网页无法正常运作
    return 'I get a number:'.$i;
}*/
/*function get_number%_($i){ // 网页无法正常运作
    return 'I get a number:'.$i;
}*/

echo add_function(1, 2); // 3
echo '<br/>';
function add_function($x, $y){
    return $x + $y;
}

$bool = FALSE;
// var_dump(get_a_bool($bool)); // Fatal error: Call to undefined function get_a_bool()
echo '<br>';
if ($bool) {
    function get_a_bool($bool){
        return $bool;
    }
}
// get_a_bool($bool); // Fatal error: Call to undefined function get_a_bool()
echo '<br>';
if ($bool) {
    var_dump(get_a_bool($bool)); // bool(true) 
    echo '<br>';
}

function have_a_function(){
    function another_function(){
        return 'I am anther function';
    }
    return 'I have a function';
}

// echo another_function(); // Fatal error: Call to undefined function another_function()
echo '<br>';
echo have_a_function(); // I have a function
echo '<br>';
echo another_function(); // I am anther function
echo '<br>';

function use_a_function($x, $y){
    return add_function($x, $y);
}

echo use_a_function(1, 2);
echo '<br>'; // 3
/*function another_function(){ // Fatal error: Cannot redeclare another_function()
    return 'I am anther function';
}*/
echo Another_function(); // I am anther function
echo '<br>';
echo Another_Function(); // I am anther function
echo '<br>';
echo Another_FUNCTION(); // I am anther function
echo '<br>';

function echo_x_10($x){
    if ($x <= 10) {
        echo $x;
        echo '<br/>';
        echo_x_10(++$x);
    }
}
echo_x_10(1);
/*
1
2
3
4
5
6
7
8
9
10
*/
  • 合法的函数名应该由以字母,数字,下划线构成且不能以数字开头。
  • 函数定义之前被调用,但如果函数的定义是有条件的则必须先定义再调用。
  • php函数具有全局作用域,即可以在函数中定义和调用函数。
  • php函数不能重复定义。
  • 函数名对大小写不敏感,但是应该保持调用和定义的统一。
  • 函数内部可以继续调用自身,这种行为被称为递归。

函数参数

通过参数可以向函数传递信息,函数的参数可以是用逗号分隔的表达式列表。

function have_no_paramater(){
    return 'This is a function without paramater';
}
echo have_no_paramater(); // This is a function without paramater
echo '<br/>';

function have_a_paramater($paramater){
    return 'This is a function has a paramater:'.$paramater;
}
echo have_a_paramater('paramater'); // This is a function has a paramater:paramater
echo '<br/>';

function person_introduction($name, $age){
    return 'my name is '.$name.', I am '.$age.' years old.';
}
echo person_introduction('lilei', '12'); // my name is lilei, I am 12 years old.
echo '<br/>';
function person_introduction_from_array($introduction){
    return 'my name is '.$introduction['name'].', I am '.$introduction['age'].' years old.';
}
echo person_introduction_from_array(['name' => 'lilei', 'age' => '12']); // my name is lilei, I am 12 years old.
echo '<br/>';

$y = 3;
function add_1($x){
    $x++;
    return $x;
}
echo add_1($y); // 4
echo '<br/>';
echo $y;
echo '<br/>'; // 3
function add_2(&$x){
    $x += 2;
    return $x;
}
echo add_2($y); // 5
echo '<br/>';
echo $y;
echo '<br/>'; // 5

function without_default_paramater($x){
    echo '$x='.$x;
    echo '<br/>';
}
without_default_paramater(); 
// Warning: Missing argument 1 for without_default_paramater(), called in ... and defined in ...
// Notice: Undefined variable: x in ...
// $x=

function with_default_paramater($x=5){
    echo '$x='.$x;
    echo '<br/>';
}
with_default_paramater(); // $x=5
with_default_paramater(7); // $x=7
$y = 4;
with_default_paramater($y); // $x=4

/*function with_default_paramater($x=$y){ // Parse error: syntax error, unexpected '$y' (T_VARIABLE) in
    echo '$x='.$x;
    echo '<br/>';
}*/


function without_default_paramater_return_value($x){
    return $x;
}
echo without_default_paramater_return_value(5); // 5
echo '<br/>';
/*function with_default_paramater($x=without_default_paramater_return_value(5)){ // Parse error: syntax error, unexpected '(', expecting ')' in
    echo '$x='.$x;
    echo '<br/>';
}*/
const NUMBER_PARAMATER = 8;
function with_default_paramater_const($x=NUMBER_PARAMATER){
    echo '$x='.$x;
    echo '<br/>';
}
with_default_paramater_const(); // $x=8

function with_two_paramater($x, $y = 4){
    echo '$x='.$x;
    echo '<br/>';
    echo '$y='.$y;
    echo '<br/>';
}
with_two_paramater(1);
with_two_paramater(3, 5);
/*
$x=1
$y=4
$x=3
$y=5
*/
function with_two_paramater_false($x = 5, $y){
    echo '$x='.$x;
    echo '<br/>';
    echo '$y='.$y;
    echo '<br/>';
}
with_two_paramater_false(1);
with_two_paramater_false(3, 5);
/*
Warning: Missing argument 2 for with_two_paramater_false(), called in 
$x=1

Notice: Undefined variable: y in 
$y=
$x=3
$y=5
*/
function with_reference_paramater(&$x = 5){
    $x++;
    echo '$x='.$x;
    echo '<br/>';
}
echo '$x='.$x;
echo '<br/>';
with_reference_paramater($x);
echo '<br/>';
echo '$x='.$x;
echo '<br/>';
/*
Notice: Undefined variable: x in D:\stone\wamp\Apache24\htdocs\test.php on line 79
$x=
$x=1

$x=1
*/

function with_another_reference_paramater($z = 5){
    $z++;
    echo '$z='.$z;
    echo '<br/>';
}
echo '$z='.$z;
echo '<br/>';
with_another_reference_paramater(&$z); 
// Fatal error: Call-time pass-by-reference has been removed; If you would like to pass argument by reference, modify the declaration of with_another_reference_paramater()
echo '<br/>';
echo '$z='.$z;
echo '<br/>';

function with_variable_paramater(...$args){
    echo '<pre>';
    print_r($args);
    echo '</pre>';
    foreach ($args as $key => $value) {
        echo '$key:'.$key.' => $value:'.$value;
        echo '<br/>';
    }
}
with_variable_paramater(1, 2, 3);
/*
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

$key:0 => $value:1
$key:1 => $value:2
$key:2 => $value:3
*/
function with_two_paramater($x, $y){
    echo '$x='.$x.', $y='.$y;
    echo '<br/>';
}
with_two_paramater(...[1, 2]); // $x=1, $y=2

function with_type_paramater(array $a){
    echo '<pre>';
    print_r($a);
    echo '</pre>';
    foreach ($a as $key => $value) {
        echo '$key:'.$key.' => $value:'.$value;
        echo '<br/>';
    }
}

with_type_paramater([1, 2, 3]);
/*
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

$key:0 => $value:1
$key:1 => $value:2
$key:2 => $value:3
*/
// with_type_paramater(1);
// Catchable fatal error: Argument 1 passed to with_type_paramater() must be of the type array, integer given, called in
// with_type_paramater(1, 2, 3);
// Catchable fatal error: Argument 1 passed to with_type_paramater() must be of the type array, integer given, called in

function with_int_paramater(int $x){
    return $x;
}

echo with_int_paramater(1); // 1
echo '<br/>';
echo with_int_paramater(1.5); // 1
declare(strict_types=1); // Fatal error: strict_types declaration must be the very first statement in the script in
echo with_int_paramater(1.5);

function callable_type_function(callable $func){
    $func();
}

function echo_hello(){
    echo 'hello';
}
callable_type_function('echo_hello'); // hello
callable_type_function('hello'); 
// Fatal error: Uncaught TypeError: Argument 1 passed to callable_type_function() must be callable, string given, called in

function with_bool_paramater(bool $a){
    var_dump($a);
}
with_bool_paramater(FALSE); // bool(false) 
echo '<br/>';
with_bool_paramater(2); // bool(true) 

function with_float_paramater(float $a){
    var_dump($a);
}
with_float_paramater(1.5); // float(1.5) 
echo '<br/>';
with_float_paramater(2); // float(2)  

function with_float_paramater(string $a){
    var_dump($a);
}
with_float_paramater('hello'); // string(5) "hello" 
echo '<br/>';
with_float_paramater(2); // string(1) "2"  
  • 函数可以没有参数。
  • 函数参数可以是任意合法的数据类型。
  • 默认情况下,函数参数通过值传递,在函数内部改变参数的值并不会改变函数外部的值。
  • 通过引用传递参数来允许函数修改它的参数值。
  • 如果想要函数的一个参数总是通过引用传递,可以在函数定义中该参数的前面加上符号&
  • 通过使用默认参数可以在函数调用时不传递参数,默认参数应该放在所有非默认参数后面,默认参数不能为变量和函数调用,默认参数也可以通过引用传递。
  • 可以通过...来为函数指定可变参数。
  • 可以指定函数参数的类型,php5.1.0开始支持arrayphp5.4.0开始支持callablephp7.0.0开始支持bool, float, int, string等。 在非严格模式下,可能的类型转换会避免使用非指定类型参数的报错,严格模式下则不会进行类型转换而直接报错,可以通过declare(strict_types=1)来开启严格模式。

函数的返回值

调用函数的目的通常是要获取一个结果,函数的返回值就提供了这样的结果,函数的返回值通过在函数体内的return指定,当函数指定了return则函数的执行就结束了。

function add_function($x, $y){
    return $x + $y;
}
echo add_function(1, 2); // 3

function add_function($x, $y): float {
    return $x + $y;
}
var_dump(add_function(1, 2)); // float(3) 
  • 可以指定函数的返回值类型。
  • 如果没有指定return则返回值为null

可变函数

通过变量来调用函数的可以被称为可变函数。

function a_function(){
    return 'a function';
}
$function_name = 'a_function';
$string = $function_name();
echo $string; // a function
echo '<br/>';
echo $function_name();

内置函数

php给我们提供了大量的内置函数,可以供我们直接使用。有的函数是由php核心提供的,无需配置直接使用,比如var_dump()。有的函数是要开启相应的扩展或在编译时指定才能使用的,比如mysql_connect()

匿名函数

php允许使用临时创建的没有名称的函数,这样的函数被称为匿名函数,也叫闭包函数。匿名函数通常被用作可执行的参数,如回调函数,当然还有其它的使用场景。

function a_function($x, $y){
    return $y($x);
}
echo a_function(1, function($z){
    return ++$z;
}); // 2

$a_function = function(){
    return 'this is a function';
};
echo $a_function(); // this is a function

$hello = 'hello';
$get_variable = function(){
    return $hello;
};
echo $get_variable(); // Notice: Undefined variable: hello in

$get_variable = function() use ($hello){
    $hello = 'world';
    return $hello;
};
echo $get_variable(); // world
echo '<br/>';
echo $hello; // hello
echo '<br/>';
$get_variable_by_reference = function() use (&$hello){
    $hello = 'world';
    return $hello;
};
echo $get_variable_by_reference(); // world
echo '<br/>';
echo $hello; // world
echo '<br/>';
$z = 8;
$get_variables_by_reference = function(&$x, $y) use (&$hello){
    $x += $y;
    $hello = 'hello';
    return $hello;
};
echo $get_variables_by_reference($z, 6); // hello
echo '<br/>';
echo $hello; // hello
echo '<br/>';
echo $z; // 14
  • 匿名函数可以赋值给一个变量,然后通过这个变量来调用这个函数。
  • 匿名函数可以通过use从父作用域继承变量或按引用继承变量,在这种情况下也可以正常的使用参数。

本文首发于公众号:programmer_cc,转载请注明出处。


微信公众号.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 156,265评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,274评论 1 288
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,087评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,479评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,782评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,218评论 1 207
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,594评论 2 309
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,316评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,955评论 1 237
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,274评论 2 240
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,803评论 1 255
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,177评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,732评论 3 229
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,953评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,687评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,263评论 2 267
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,189评论 2 258

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,083评论 18 139
  • //Clojure入门教程: Clojure – Functional Programming for the J...
    葡萄喃喃呓语阅读 3,489评论 0 7
  • php usleep() 函数延迟代码执行若干微秒。 unpack() 函数从二进制字符串对数据进行解包。 uni...
    思梦PHP阅读 1,965评论 1 24
  • 最近的天气冷了许多,下班骑单车穿过多个路口,指尖冷冻,寒意袭人,告诉自己冬天来了。归来!细想多思,小感。 一首歌,...
    纸简书生阅读 316评论 0 0
  • 从没有认真想过去爱一个人,虽然也曾羡慕别人如何被体贴,可我更喜欢一个人去书店不被打扰,吃饭不用考虑别人的口味,花钱...
    在沉默中肆意阅读 340评论 0 1