Skip to content
Advertisement

Can PHP’s interactive mode run code in a namespace?

While in PHP’s interactive mode, I tried the following:

php > namespace MyNamespace;
php > class Throwable {}

This results in a fatal error:

PHP Fatal error:  Cannot declare class Throwable, because the name is already in use in php shell code on line 1

However, the following code, when in a PHP file, executes without errors:

<?php
namespace MyNamespace;
class Throwable {}

Therefore, is it possible to somehow set a namespace while in interactive mode? Or, is all code in interactive mode run in the global space regardless of a previous namespace definition?

Advertisement

Answer

For this to work, you have to apply the example given in the documentation that allows for combining namespaced and unnamespaced code:

namespace MyNamespace {
    class Throwable {}
}

It looks like this when you type it:

> namespace Mynamespace {
{ class Throwable {}
{ }
>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement