クラス内で定義した変数を、同じクラス内の変数で呼び出せません。
何が原因でしょうか?
コード
構成は下記です。
ルートディレクトリ直下に全てのファイルがあります。
- common.php: class自体が書かれたファイル
- foo.json: classのコンストラクタで指定するjsonファイル
- index.php: classを呼び出すファイル。
最初に、constructでjsonを読み込み複数の配列を取得します。
別のタイミングで、getFoo()
で配列から対象の配列のみ返すと言う処理をします。
common.php
php
1<?php 2class CommonFunctions{ 3 private $_foo = []; 4 5 function __construct($dir) { 6 $this->_foo = json_decode(file_get_contents($dir . '/foo.json'), true); 7 // var_dump($this->_foo)で、jsonの中身を見れることは確認済み。 8 } 9 10 // jsonファイルから該当する配列を取得する 11 public function getFoo($id){ 12 $foos = $this->_foo; 13 $targetFoo = array_filter($foos, function($var) use ($id){ 14 return $var['id'] == $id; 15 }); 16 17 $result = []; 18 if(count($targetFoo) > 0) { 19 $result = current($targetFoo); 20 }; 21 22 return $result; 23 } 24} 25 ?> 26
foo.json
json
1[ 2 { 3 "id": 1, 4 "name": "test_1", 5 }, 6 { 7 "id": 2, 8 "name": "test_2", 9 } 10]
index.php
php
1<?php 2 require(__DIR__ . '/common.php'); 3 $commonFunctions = new CommonFunctions(__DIR__); 4 $getFoo = $commonFunctions::getFoo(1); 5 var_dump($getFoo); 6?>
エラー内容
Fatal error: Uncaught Error: Using $this when not in object context
selfで呼び出そうとした場合
蛇足かもしれませんが、self::_scenes
でも確認しました。
Fatal error: Uncaught Error: Undefined class constant '_scenes'
回答2件
あなたの回答
tips
プレビュー