note 110644 deleted from language.namespaces.nsconstants by aharvey
| From: | aharvey@php.net | Date: | Mon, 19 Nov 2012 01:12:49 +0000 |
| Subject: | note 110644 deleted from language.namespaces.nsconstants by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-192028@lists.php.net to get a copy of this message | ||
Note Submitter: rayro at gmx dot de
----
You can use debug_backtrace() to get the previously used namespaces. Tested with php 5.4.8:
<?php
namespace {
header('Content-Type:text/plain');
function get_namespace($i=0)
{
$bt = debug_backtrace(2,2+$i)[$i+1];
$ns = ($bt['class']?$bt['class']:$bt['function']);
$ns = substr($ns,0,strrpos($ns,'\\'));
return '\\'.$ns;
}
function get_prev_namespace($i=1) {
$bt = debug_backtrace(2,2+$i)[$i+1];
$ns = ($bt['class']?$bt['class']:$bt['function']);
$ns = substr($ns,0,strrpos($ns,'\\'));
return '\\'.$ns;
}
function get_latest_namespaces() {
$ns = array();
foreach(debug_backtrace(2) as $bt) {
$nsx = ($bt['class']?$bt['class']:$bt['function']);
$ns[] = rtrim('\\'.substr($nsx,0,strrpos($nsx,'\\')),'\\');
}
return array_merge(array_filter($ns));
}
}
namespace project\any {
class B {
function __construct() {
var_dump(get_namespace());
var_dump(get_prev_namespace());
var_dump(get_latest_namespaces());
}
}
}
namespace project\thing {
class C {
function __construct() {
new \project\any\B();
}
}
}
namespace project\you {
class D {
function __construct() {
new \project\thing\C();
}
}
}
namespace project\want {
class E {
function __construct() {
new \project\you\D();
}
}
$e = new E();
}
/*
should output:
string(12) "\project\any"
string(14) "\project\thing"
array(4) {
[0]=>
string(12) "\project\any"
[1]=>
string(14) "\project\thing"
[2]=>
string(12) "\project\you"
[3]=>
string(13) "\project\want"
}
*/
?>