So I'm targetting my compiler to PHP and I'm having some problems with namespaces.
They look something like this in my language:
package Foo
{
package Bar
{
class X { }
}
class Y { }
}
Of course, PHP doesn't handle nested namespaces. What's the best way to translate this code so it still works in PHP?
I should note that all files are compiled into a single PHP file in the end. One caveat of this is that I'll have to go back to the global namespace after I've closed a package, and I haven't found any documentation about how to do that. It seems to me that in PHP, once you declare a namespace, it applies to the whole file.
It's true that "Namespace declarations cannot be nested".Namespacing is used to avoid conflicting definitions and introduce more flexibility and organization in your code.The brackets surrounding the namespace code block are completely optional.If you want to translate your code to run able in php. You can write like:
namespace Foo\Bar;
class X{
// Your properties
}
class Y {
// Your properties
}
If you need more information you can see this link well written by Elias Zerrouq with example http://code.tutsplus.com/tutorials/namespacing-in-php--net-27203
Zotoaster it is quite possible to do what you desire; however, my solution would rely on the psr-4 autoloading solution. With this, by placing your files in the appropriate folders, you would be able to do the following at the start of the php file:
use Foo\Bar\X;
use Foo\Y;
Thereafter you can instantiate the classes accordingly:
$x = new X();
$y = new Y();
You can read more on how to use namespaces here: http://www.php-fig.org/psr/psr-4/ Furthermore, you could use composer to handle the "dirty work" for you, i.e. all the auto loading: https://getcomposer.org/doc/01-basic-usage.md#autoloading
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