質問編集履歴
3
処理を再現できる状態に追記
title
CHANGED
File without changes
|
body
CHANGED
@@ -2,23 +2,31 @@
|
|
2
2
|
何が原因でしょうか?
|
3
3
|
|
4
4
|
## コード
|
5
|
+
|
6
|
+
構成は下記です。
|
7
|
+
ルートディレクトリ直下に全てのファイルがあります。
|
8
|
+
- common.php: class自体が書かれたファイル
|
9
|
+
- foo.json: classのコンストラクタで指定するjsonファイル
|
10
|
+
- index.php: classを呼び出すファイル。
|
11
|
+
|
5
12
|
最初に、constructでjsonを読み込み複数の配列を取得します。
|
6
13
|
別のタイミングで、```getFoo()```で配列から対象の配列のみ返すと言う処理をします。
|
7
14
|
|
15
|
+
### common.php
|
8
16
|
```php
|
9
17
|
<?php
|
10
18
|
class CommonFunctions{
|
11
19
|
private $_foo = [];
|
12
20
|
|
13
21
|
function __construct($dir) {
|
14
|
-
$this->_foo = json_decode(file_get_contents($dir . '/
|
22
|
+
$this->_foo = json_decode(file_get_contents($dir . '/foo.json'), true);
|
15
23
|
// var_dump($this->_foo)で、jsonの中身を見れることは確認済み。
|
16
24
|
}
|
17
25
|
|
18
|
-
//
|
26
|
+
// jsonファイルから該当する配列を取得する
|
19
27
|
public function getFoo($id){
|
20
|
-
$
|
28
|
+
$foos = $this->_foo;
|
21
|
-
$targetFoo = array_filter($
|
29
|
+
$targetFoo = array_filter($foos, function($var) use ($id){
|
22
30
|
return $var['id'] == $id;
|
23
31
|
});
|
24
32
|
|
@@ -34,6 +42,30 @@
|
|
34
42
|
|
35
43
|
```
|
36
44
|
|
45
|
+
### foo.json
|
46
|
+
```json
|
47
|
+
[
|
48
|
+
{
|
49
|
+
"id": 1,
|
50
|
+
"name": "test_1",
|
51
|
+
},
|
52
|
+
{
|
53
|
+
"id": 2,
|
54
|
+
"name": "test_2",
|
55
|
+
}
|
56
|
+
]
|
57
|
+
```
|
58
|
+
|
59
|
+
### index.php
|
60
|
+
```php
|
61
|
+
<?php
|
62
|
+
require(__DIR__ . '/common.php');
|
63
|
+
$commonFunctions = new CommonFunctions(__DIR__);
|
64
|
+
$getFoo = $commonFunctions::getFoo(1);
|
65
|
+
var_dump($getFoo);
|
66
|
+
?>
|
67
|
+
```
|
68
|
+
|
37
69
|
## エラー内容
|
38
70
|
> Fatal error: Uncaught Error: Using $this when not in object context
|
39
71
|
|
2
クラス内の変数を単純変数に入れて試してみましたので更新します。
title
CHANGED
File without changes
|
body
CHANGED
@@ -17,7 +17,8 @@
|
|
17
17
|
|
18
18
|
// シーンjsonから特定の画像を抜き出す
|
19
19
|
public function getFoo($id){
|
20
|
+
$scenes = $this->_foo;
|
20
|
-
$targetFoo = array_filter($
|
21
|
+
$targetFoo = array_filter($scenes, function($var) use ($id){
|
21
22
|
return $var['id'] == $id;
|
22
23
|
});
|
23
24
|
|
1
追記
title
CHANGED
File without changes
|
body
CHANGED
@@ -34,10 +34,10 @@
|
|
34
34
|
```
|
35
35
|
|
36
36
|
## エラー内容
|
37
|
-
```php
|
38
|
-
Fatal error: Uncaught Error: Using $this when not in object context
|
37
|
+
> Fatal error: Uncaught Error: Using $this when not in object context
|
39
|
-
```
|
40
38
|
|
41
39
|
### selfで呼び出そうとした場合
|
40
|
+
|
42
|
-
```
|
41
|
+
蛇足かもしれませんが、```self::_scenes```でも確認しました。
|
42
|
+
|
43
|
-
Fatal error: Uncaught Error: Undefined class constant '_scenes'
|
43
|
+
> Fatal error: Uncaught Error: Undefined class constant '_scenes'
|