<?php
namespace Random\Namespace;
When I run this code on 3v4l.org (https://3v4l.org/kk0bD) it works fine on PHP 8.0.0+ but on PHP >= 5.4.0 and PHP < 8.0.0 I get this error:
Parse error: syntax error, unexpected 'Namespace' (T_NAMESPACE), expecting identifier (T_STRING)
I don’t understand. namespaces have been around in PHP since PHP 5.3.0.
Any ideas?
>Solution :
Until PHP 8.0, every component in a namespace was considered as a distinct name, and each part could not use any of the list of reserved keywords.
In this case, the namespace Random\Namespace contains the reserved name "Namespace" as one of its components, so is rejected by the parser.
In PHP 8.0, a change to the parser was introduced where the entire namespace name is treated as a single token (as part of a general trend to making keywords reserved in as few contexts as possible). So for PHP 8.x, the name is parsed in one go as "Random\Namespace", which is not reserved.
The linked proposal notes that the keyword namespace is still reserved at the start of namespace names, because it would cause ambiguity in some contexts, so namespace Namespace\Random; is still an error.