-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction-modifiers-in-php.html
60 lines (50 loc) · 2.06 KB
/
function-modifiers-in-php.html
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Function modifiers in php</title>
<link rel="stylesheet" href="css/css.css" type="text/css" media="all">
<link rel="stylesheet" href="css/prism.css" type="text/css" media="all">
<link rel="stylesheet" href="css/latex.css" type="text/css" media="all">
</head>
<body>
<h1 id="function-modifiers-in-php">Function modifiers in php</h1>
<p>These function calls happens to be valid php syntax. Each of these is a call to the same function <code>decor</code>.</p>
<pre><code class="language-php"><?php
+decor(); // #=> Called with "+".
-decor(); // #=> Called with "-".
!decor(); // #=> Called with "!".
@decor(); // #=> Called with "@".
~decor(); // #=> Called with "~".
decor(); // #=> Called as regular.
</code></pre>
<p>A project <a href="https://kint-php.github.io/kint/advanced/#modifiers">knit</a>
decided to take advantage of this.</p>
<p>There is no trick. Function itself just
checks on how it was called and then performs based on that.</p>
<h2 id="overview">Overview</h2>
<p>An oversimplified example below illustrates mechanism.</p>
<pre><code class="language-php"><?php
function decor() {
[['file' => $file, 'line' => $line]] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
$file = new SplFileObject($file);
$file->seek($line - 1);
$line = $file->current();
switch ($line[strpos($line, __FUNCTION__) - 1]) {
case '+': echo 'Called with "+".'; break;
case '-': echo 'Called with "-".'; break;
case '!': echo 'Called with "!".'; break;
case '@': echo 'Called with "@".'; break;
case '~': echo 'Called with "~".'; break;
default: echo 'Called as regular.'; break;
}
echo PHP_EOL;
return 0;
}
</code></pre>
<blockquote>
<p>When <code>~</code> operator is used, function must return integer.</p>
</blockquote>
<script src="js/prism.js"></script>
</body>
</html>