//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.
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");
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With