PHP アプリケーションには、以前に呼び出された関数に応じて、何か問題が発生した場合に別のエラー メッセージを表示する必要がある場所がいくつかあります。
たとえば、次の例では、「ファイル」に対して直接 startEdit() 関数を呼び出し、ファイルがロックされている場合、特定のエラー メッセージが返されます。ただし、startEdit() 関数が親の「フォルダ」で startEdit() 関数の結果として呼び出された場合、別のエラー メッセージが表示されます (以下の例を参照)。
<?php
class folder{
public $files = array();
public function startEdit(){
//when we start editing a folder, start editing all files within it
foreach($this->files as $file){
$file->startEdit();
}
}
}
class file{
public $isLocked = true;
public function startEdit(){
try{
//if the file is locked we need to throw an exception
if($this->isLocked==1){
//loop through the stack trace to see if this was called from the folder class.
foreach(debug_backtrace() as $frame){
if($frame['class']=='folder'){
throw new Exception("Cannot edit this folder because one of the files within it are locked");
}
}
//if not called from the folder class then throw a different error
throw new Exception("This file is locked");
}
}catch(Exception $e){
exit("Exception: ".$e->getMessage());
}
}
}
//create a new folder
$folder = new folder();
//put some files within it
$file1 = new file();
$file2 = new file();
$folder->files = array($file1, $file2);
//start editing the folder - should return the message 'Cannot edit this folder because one of the files within it are locked'
$folder->startEdit();
//try editing one of the files - should return the message 'This file is locked'
$file1->startEdit();
?>
これは、私がやろうとしていることの非常に単純化されたバージョンです。私のアプリケーションでは、エラー メッセージは、5 または 6 スタック フレーム前に呼び出された関数に依存する可能性があります。
私の質問は - これは物事を行う有効な方法ですか? これを達成するためのより良い方法はありますか?
ありがとう!
アップデート
明確にするために、実際のスタック トレースをユーザーに表示したくありません。スタック トレースを使用して、ユーザーにとってより役立つメッセージを作成したいと考えています。それを行うもう1つの方法は、各関数に別のパラメーターを渡して、どこから呼び出されたかを伝えることでしょうか?
他の誰かが同様のことを試みましたか? これに関する助けがあれば大歓迎です!