gpt4 book ai didi

PHP 相当于 python 装饰器?

转载 作者:太空狗 更新时间:2023-10-29 18:04:15 25 4
gpt4 key购买 nike

我希望能够用另一个函数包装一个 PHP 函数,但保留其原始名称/参数列表不变。

例如:

function A() {
print "inside A()\n";
}

function Wrap_A() {
print "Calling A()\n";
A();
print "Finished calling A()\n";
}

// <--- Do some magic here (effectively "A = Wrap_A")

A();

输出:

Calling A()
inside A()
Finished calling A()

最佳答案

这是我在 php 中模仿 python 装饰器的方法。

function call_decorator ($decorator, $function, $args, $kwargs) {

// Call the decorator and pass the function to it
$decorator($function, $args, $kwargs);
}

function testing ($args, $kwargs) {
echo PHP_EOL . 'test 1234' . PHP_EOL;
}

function wrap_testing ($func, $args, $kwargs) {

// Before call on passed function
echo 'Before testing';

// Call the passed function
$func($args, $kwargs);

// After call on passed function
echo 'After testing';
}

// Run test
call_decorator('wrap_testing', 'testing');

输出:

Before testing
testing 1234
After testing

通过此实现,您还可以使用匿名函数执行类似的操作:

// Run new test
call_decorator('wrap_testing', function($args, $kwargs) {
echo PHP_EOL . 'Hello!' . PHP_EOL;
});

输出:

Before testing
Hello!
After testing

最后,如果您愿意,您甚至可以做这样的事情。

// Run test
call_decorator(function ($func, $args, $kwargs) {
echo 'Hello ';
$func($args, $kwargs);
}, function($args, $kwargs) {
echo 'World!';
});

输出:

Hello World!

通过上面的构造,如果需要,您可以将变量传递给内部函数或包装器。这是带有匿名内部函数的实现:

$test_val = 'I am accessible!';

call_decorator('wrap_testing', function($args, $kwargs){
echo $args[0];
}, array($test_val));

在没有匿名函数的情况下,它的工作方式完全相同:

function test ($args, $kwargs) {
echo $kwargs['test'];
}

$test_var = 'Hello again!';

call_decorator('wrap_testing', 'test', array(), array('test' => $test_var));

最后,如果您需要修改 wrapper 或 wrappie 中的变量,只需通过引用传递变量即可。

没有引用:

$test_var = 'testing this';
call_decorator(function($func, $args, $kwargs) {
$func($args, $kwargs);
}, function($args, $kwargs) {
$args[0] = 'I changed!';
}, array($test_var));

输出:

testing this

引用:

$test_var = 'testing this';
call_decorator(function($func, $args, $kwargs) {
$func($args, $kwargs);
}, function($args, $kwargs) {
$args[0] = 'I changed!';

// Reference the variable here
}, array(&$test_var));

输出:

I changed!

这就是我现在所拥有的,它在很多情况下都非常有用,如果你愿意,你甚至可以将它们包装多次。

关于PHP 相当于 python 装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1425303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com