Blogger Information
Blog 8
fans 0
comment 0
visits 6546
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
9月29日匿名函数与闭包,多个命名空间场景、类与对象关系
Laravel框架学些
Original
459 people have browsed it

今天学习了匿名函数与闭包,多个空间场景,类与对象概念

  1. 自写案例演示匿名函数的三个应用场景

    匿名函数有三个应用场景

    1.1、值的应用


    实例

    $sum = function ($a,$b){
        return $a +$b;
    };
    echo $sum(10,20);

    运行实例 »

    点击 "运行实例" 按钮查看在线实例

    运行结果:30

    1.2、回调函数


    实例

    <?php
    $arr = [6,1,8,12,19];
    usort($arr, function ($a, $b){
    
       return  $b - $a;
    });
    
    echo '<pre>' . print_r($arr, true);
    ?>

    运行实例 »

    点击 "运行实例" 按钮查看在线实例

6.png

3.闭包的使用----获取父作用域中的变量值

实例

<?php

$name = 'teacher';
$f1 = function () use ($name) {
    return $name;
};
echo $f1();
echo '<hr>';
function demo() {
    $email = '473288703@qq.com';
    return function () use($email){
        return $email;};

}
echo demo() ();

?>

运行实例 »

点击 "运行实例" 按钮查看在线实例

7.png

2.多个命名空间的演示

在PHP中,命名空间用来解决在编写类库或应用程序时创建可重用的代码如类或函数时碰到的两类问题:

用户编写的代码与PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲突。

为很长的标识符名称(通常是为了缓解第一类问题而定义的)创建一个别名(或简短)的名称,提高源代码的可读性

实例

namespace red;

function sum($a, $b)
{
return $a + $b;
}

namespace green;
function sum($a, $b)
{
    return $a*$b;
}
echo \red\ sum(30,40);

?>

运行实例 »

点击 "运行实例" 按钮查看在线实例

运行结果:70

总结: 感觉命名空间像PC机 文件路径,相同的文件名可以在不同的目录下存在,但是不能够在同一个路径同一目录下存在

Correction status:qualified

Teacher's comments:总结的不错, 在项目要灵活应用
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!