Thanks to the pos dupe link I managed to do some digging to really get what I want. It seems with debug_backtrace()
it well.. traces back through each function call. E.g.
fileA.php
class Bar
{
public function foo()
{
echo '<pre>'. print_r(debug_backtrace(), 1) .'</pre>';
return 'hi';
}
}
fileB.php
require_once 'fileA.php';
$bar = new \Bar();
echo $bar->foo();
This outputs:
Array
(
[0] => Array
(
[file] => /var/www/testing/test/fileB.php
[line] => 5
[function] => foo
[class] => Bar
[object] => Bar Object ()
[type] => ->
[args] => Array ()
)
)
hi
This is for the most part, perfect. However, this doesn't gurantee results as the array increases per stack.
E.g. FileC.php calls function in FileB.php which in turn, calls a function in
FileA.php
However, I noted with use of the function that the most desirable one is the end element in the array. With that in mind, I've set up a few functions to mimic functionality of the magic constants, without using any magic.
Set up for use of functions:
$trace = debug_backtrace();
$call = end($trace);
Directory (__DIR__
):
# $trace = $call['file']
protected function getDir($trace)
{
$arr = explode('/', $trace);
$file = end($arr);
$directory = [];
$i = 0;
foreach ($arr as $data)
{
if ($data !== $file) {
$directory[] = isset($output) ? $output[$i - 1] . '/' . $data : $data;
$i++;
}
}
return 'DIRECTORY: '. implode('/', $directory);
}
File (__FILE__
)::
# $trace = $call['file']
protected function getFile($trace)
{
$arr = explode('/', $trace);
$file = end($arr);
return 'FILE: '. $file;
}
Function/Method (__FUNCTION__
|| __METHOD__
)::
# $trace = $call
protected function getFunction($trace)
{
$output = 'FUNCTION: '. $trace['function'] ."\n";
foreach ($trace['args'] as $key => $arguments)
{
foreach ($arguments as $k => $arg)
{
if (!is_array($arg)) {
$output .= 'ARGS ('. $k .'): '. $arg ."\n";
}
}
}
return $output;
}
Namespace (__NAMESPACE__
):
# $trace = $call['class']
protected function getNamespace($trace)
{
$arr = explode('\\', $trace);
$class = end($arr);
$namespace = [];
$i = 0;
foreach ($arr as $data)
{
if ($data !== $class) {
$namespace[] = isset($output) ? $output[$i - 1] . '/' . $data : $data;
$i++;
}
}
return 'NAMESPACE: '. implode('\\', $namespace);
}
Class (__CLASS__
):
# $trace = $call['class']
protected function logClass($trace)
{
if (strpos($trace, '\\') !== false) {
$arr = explode('\\', $trace);
$class = end($arr);
} else {
$class = $trace;
}
$return = 'CLASS: '. $class;
}
Missing Magic Constants:
Line is accessible (as you'll see from print_r($call, 1)
) but I wasn't in need/interested. Trait is more or less the same as __NAMESPACE__
in my uses, so again, it wasn't interested in creating a function for it.
Notes:
This is part of a class I made that makes use of the protected function via public accessible functions - please ignore :)
These functions could be cleaned up (e.g. instead of $trace = $call['file'], use $file as param)