PHP花里胡哨

类方法/属性动态调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class A
{
public $two_closure = NULL;

public function __construct()
{
$this->two_closure = function ($name) {
echo "this is closure, and the name is {$name}" . PHP_EOL;
};
}

public function one_step()
{
echo "this is one" . PHP_EOL;
}
}

// 动态调用常规方法
$num = 'one';
$methodName = "{$num}_step";
(new A())->$methodName(); // this is one


// 动态调用属性(当属性是闭包时)
$num = 'two';
$propName = "{$num}_closure";
((new A())->$propName)('haha'); // this is closure, and the name is haha
  • Copyrights © 2019-2024 Klusfq
  • Visitors: | Views: