Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php get namespace of included file

Tags:

namespaces

php

//file foo.php
<?php
namespace foo;
class foo{
    function __construct(){
        echo "hello";
    }
}
?>

//file index.php
<?php
require_once("foo.php");
echo __NAMESPACE__;
?>

My question is, from my index.php file, is it possible to know what the namespace of foo.php is without reading the file contents and doing a regular expression on it? That just seems like a lot of overhead.

///EDIT

I'd really like to be able to dynamically add the namespace to the included file.

<?php
namespace dynamic;
require_once("foo.php");
echo __NAMESPACE__;
?>

I want to allow for third-party plugins, but php namespaces seems terrible. I don't want to have the plugin editors have to create a namespace.

like image 600
Senica Gonzalez Avatar asked Dec 22 '10 18:12

Senica Gonzalez


3 Answers

No. But you could trick it this way round:

//file foo.php
<?php
  namespace foo;
  //...
  return __NAMESPACE__;  // must be last line
?>

And for reading it out:

//file index.php
<?php
  $ns = require_once("foo.php");
like image 187
mario Avatar answered Oct 24 '22 19:10

mario


Well, you could scan the class namespace. It contains namespaces. It's the PHPUnit way of doing things. So i.e.:

$namespaces = get_current_namespaces();

include 'plugin/main.php';

$newNamespaces = get_current_namespaces(); 
array_diff($namespaces, $newNamespaces)

Here is how you can implement get_current_namespaces(): is it possible to get list of defined namespaces

like image 33
Artur Bodera Avatar answered Oct 24 '22 19:10

Artur Bodera


If you know the file, you can simply extract the namespace form it :).

function extract_namespace($file) {
    $ns = NULL;
    $handle = fopen($file, "r");
    if ($handle) {
        while (($line = fgets($handle)) !== false) {
            if (strpos($line, 'namespace') === 0) {
                $parts = explode(' ', $line);
                $ns = rtrim(trim($parts[1]), ';');
                break;
            }
        }
        fclose($handle);
    }
    return $ns;
}

And you will be not constrain to return something at the end of file that can be broke from exit or other return instructions.

like image 24
onalbi Avatar answered Oct 24 '22 18:10

onalbi