Decorator函数
来源:互联网 发布:厦大网络教学平台登录 编辑:程序博客网 时间:2024/06/14 17:58
什么是 decorator函数?比如说,我想1.创建一个函数,2.运行过程中有某个函数把关,3.运行函数完成一定的功能;但作为函数的创建者和使用者,我并不希望运行函数时去关注把关者,而只关注函数本身;另外,把关者可能差别非常大。更进一步说,我们希望能用任意一个把关函数,去“装饰”任意另一个函数。
下面这个例子很好说明问题,testfunc函数只要关注自己即可, decorate做了什么事情(比方说可以直接改成是否要给予某个授权或放行),testfunc并没有直接参与。
<?php
session_start();
$decorate =function($func) {
return function() use ($func) { //加上这一句之后,$decorate返回就是一个函数,而不是值或空值。
if ($_SESSION['is_decorated'] == true){
$args = func_get_args($func);
call_user_func_array($func, $args);
}
else {
echo "Access Denied, decoratenot allowed!";
}
};
};
$testfunc =function($content) {
echo "Testfunc get content:$content"."<br>";
};
$testfunc =$decorate($testfunc);
$_SESSION['is_decorated']= true;
$testfunc('test01is decorated');
$_SESSION['is_decorated']= false;
$testfunc('test02');
?>
运行上面的代码,你会得到下面的结果,
testfunc content: test01 is charged
Access Denied, decorate allowed!
- Decorator函数
- Python decorator 1: 函数
- JavaScript-装饰器函数(Decorator)
- python 统计函数时间 decorator
- Decorator
- decorator
- Decorator
- Decorator
- Decorator
- Decorator
- Decorator
- decorator
- Decorator
- decorator
- decorator
- decorator
- Decorator
- Decorator
- Python画图
- python time datetime 使用
- otter系列—otter 基本介绍
- 740. Delete and Earn
- bzoj1041: [HAOI2008]圆上的整点
- Decorator函数
- 【Java学习笔记】父类引用指向子类对象之属性
- NDK开发系列二
- Hadoop读书笔记(一)——Hadoop分布式文件系统
- CS231n A2: Global name 'col2im_6d_cython' is not defined解决(Mac)
- python dict常用
- R语言UTF-8各种问题解决方法
- TypeError: data type "datetime" not understood
- canvas (1) 画一些简单的图形