I have this function in my class:
logMagic($mode)
{
# mode
# 1 = all, 2 = dir, 3 = file etc.
# this is wrapped inside a switch statement
# for eases sake here's the case 1: code
$log['dir'] = 'DIRECTORY: '. __DIR__;
$log['file'] = 'FILE: '. __FILE__;
$log['meth'] = 'METHOD: '. __METHOD__;
$log['fnc'] = 'FUNCTION: '. __FUNCTION__;
$log['ns'] = 'NAMESPACE: '. __NAMESPACE__;
$log['cl'] = 'CLASS: '. __CLASS__;
return $log;
}
This is in a foo.php file. I then have a bar.php file where I call and init the class to use this function:
require_once 'foo.php';
$logger = new \Logger('trey.log', 'var/logs');
$logger->logMagic($logger::ALL);
My problem with this is, this will output (in a log file):
DIRECTORY: /var/www/dir
FILE: /var/www/dir/foo.php
METHOD: Logger::logMagic
FUNCTION: logMagic
NAMESPACE:
CLASS: Logger
My expected output was that it would return
DIRECTORY: /var/www/dir
FILE: /var/www/dir/bar.php
METHOD:
FUNCTION:
NAMESPACE:
CLASS:
Reading the docs does clarify this to me that this is normal.
Is there any way I can use magic constants from fileb.php in filea.php, without passing params to the function?
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.This outputs:
This is for the most part, perfect. However, this doesn't gurantee results as the array increases per stack.
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:
Directory (
__DIR__):File (
__FILE__)::Function/Method (
__FUNCTION__||__METHOD__)::Namespace (
__NAMESPACE__):Class (
__CLASS__):Missing Magic Constants:
__LINE____TRAIT__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)