note 110644 added to language.namespaces.nsconstants

From: Date: Fri, 16 Nov 2012 12:57:58 +0000
Subject: note 110644 added to language.namespaces.nsconstants
Groups: php.notes 
Request: Send a blank email to php-notes+get-192010@lists.php.net to get a copy of this message
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" } */ ?> ---- Server IP: 69.147.83.199 Probable Submitter: 83.236.215.77 ---- Manual Page -- http://www.php.net/manual/en/language.namespaces.nsconstants.php Edit -- https://master.php.net/note/edit/110644 Del: integrated -- https://master.php.net/note/delete/110644/integrated Del: useless -- https://master.php.net/note/delete/110644/useless Del: bad code -- https://master.php.net/note/delete/110644/bad+code Del: spam -- https://master.php.net/note/delete/110644/spam Del: non-english -- https://master.php.net/note/delete/110644/non-english Del: in docs -- https://master.php.net/note/delete/110644/in+docs Del: other reasons-- https://master.php.net/note/delete/110644 Reject -- https://master.php.net/note/reject/110644 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#192010) next »