回答編集履歴

1

修正

2015/06/29 06:12

投稿

flat
flat

スコア617

test CHANGED
@@ -1 +1,147 @@
1
- 質問内容へ追記にある内容で一先ず自己解決しました。
1
+ 自分なりに調べて試してみた結果、下記の内容で自己解決しました。
2
+
3
+
4
+
5
+ また、[PHPマニュアルにある変数のスコープの例](http://php.net/manual/ja/language.variables.scope.php#example-113)にある変数$aと$bは、明記されていないだけでグローバル宣言がされているものと解釈する事にしました。
6
+
7
+
8
+
9
+ **1. グローバル宣言した変数を参照**
10
+
11
+ ```lang-PHP
12
+
13
+ global $success, $failure; // この変数をグローバル変数にするという宣言
14
+
15
+ $success = 'Yes!';
16
+
17
+ $failure = 'Sorry...';
18
+
19
+
20
+
21
+ function please_marry_me( $result=true ) {
22
+
23
+ global $success, $failure; // ローカル変数ではなくグローバル変数を使うという指示
24
+
25
+ $reaction;
26
+
27
+ if ( $result === true ) {
28
+
29
+ $reaction = '<p>' . $success . '</p>';
30
+
31
+ } elseif ( $result === false ) {
32
+
33
+ $reaction = '<p>' . $failure . '</p>';
34
+
35
+ } else {
36
+
37
+ $reaction = '<p>Please enter a true or false.</p>';
38
+
39
+ }
40
+
41
+ return $reaction;
42
+
43
+ }
44
+
45
+
46
+
47
+ echo please_marry_me( true );
48
+
49
+ ```
50
+
51
+
52
+
53
+ **2. クロージャ(無名関数)による変数の引き継ぎ**
54
+
55
+ ```lang-PHP
56
+
57
+ /*
58
+
59
+ * 引き継がれた変数の値は関数を定義した時点のもの
60
+
61
+ * 引き継がれた変数の値は関数の中では変更可能(関数の外にある変数には反映されない)
62
+
63
+ * 参照渡し(&$success)で引き継ぐと、関数を定義した後で変更した変数の値が呼び出した関数に反映される
64
+
65
+ * クロージャを変数に代入しているので上書きされるとクロージャを呼び出せなくなる
66
+
67
+ */
68
+
69
+ $success = 'Yes!';
70
+
71
+ $failure = 'Sorry...';
72
+
73
+
74
+
75
+ $please_marry_me = function( $result=true ) use ( $success, $failure ) {
76
+
77
+ $reaction;
78
+
79
+ if ( $result === true ) {
80
+
81
+ $reaction = '<p>' . $success . '</p>';
82
+
83
+ } elseif ( $result === false ) {
84
+
85
+ $reaction = '<p>' . $failure . '</p>';
86
+
87
+ } else {
88
+
89
+ $reaction = '<p>Please enter a true or false.</p>';
90
+
91
+ }
92
+
93
+ return $reaction;
94
+
95
+ }; // 変数なのでセミコロンの入れ忘れに要注意
96
+
97
+
98
+
99
+ $success = 'Yes, of course!';
100
+
101
+ echo $success; // Yes of course!
102
+
103
+ echo $please_marry_me( true ); // Yes!
104
+
105
+ ```
106
+
107
+
108
+
109
+ **3. $GLOBALS(スーパーグローバル)による変数の参照**
110
+
111
+ ```lang-PHP
112
+
113
+ global $success, $failure; // グローバル宣言は必要
114
+
115
+ $success = 'Yes!';
116
+
117
+ $failure = 'Sorry...';
118
+
119
+
120
+
121
+ function please_marry_me( $result=true ) {
122
+
123
+ $reaction;
124
+
125
+ if ( $result === true ) {
126
+
127
+ $reaction = '<p>' . $GLOBALS['success'] . '</p>';
128
+
129
+ } elseif ( $result === false ) {
130
+
131
+ $reaction = '<p>' . $GLOBALS['failure'] . '</p>';
132
+
133
+ } else {
134
+
135
+ $reaction = '<p>Please enter a true or false.</p>';
136
+
137
+ }
138
+
139
+ return $reaction;
140
+
141
+ }
142
+
143
+
144
+
145
+ echo please_marry_me( true );
146
+
147
+ ```