On Fri, Feb 26, 2021 at 12:36 PM Manuel Canga <p...@manuelcanga.dev> wrote:

>  >
>  > Hi,
>  >
>  > Note that (typos aside) this example cannot work as-is, because
> `static::namespace` (like `static::class`) cannot be resolved at
> compile-time, and therefore cannot be assigned to a constant.
>  >
>  > More generally, in the various examples you provided, the namespace is
> not resolved at compile-time: it is either static::namespace or
> $fullClassName::namespace where $fullClassName is provided by the
> autoloader. As such, instead of a ::namespace magic class constant, it
> might be more appropriate to have a helper function, say `get_namespace()`,
> which has the additional benefit to work not only on (fully qualified)
> class names, but also on function, constant and namespace names (in the
> case of namespace names, it would return the name of the parent namespace).
>  >
>  > —Claude
>  >
>  >
>
> Hi, Claude,
>
> That's sound great. Something like dirname[1] but with namespaces.
>
> But...in that case, I also add a new function like basename but with
> namespaces. Example autoload for WordPress :
>
> ```
> function autoload( $ful_class_name ) {
>
> $class_ path = str_replace('\\', '/', get_namespace( $ful_class_name ) );
> $class_name = strtolower( get_base_namespace( $ful_class_name ) );
>
>   require "{$class_path}/class-{$class_name}.php";
>
> }```
>
> [1]: https://www.php.net/manual/es/function.dirname.php
> [2]: https://www.php.net/manual/es/function.basename.php
>

Hi,

For that example (and most others), you're manipulating file paths anyway,
and assume that the FQCN is at least one level deep (i.e. not top-level),
so you may as well start with `$p = str_replace('\\', \DIRECTORY_SEPARATOR,
$fqcn);` then use `dirname($p)` and/or `basename($p)`.

Now for the (rarer) cases when you actually want the namespace name and/or
the unqualified class name, I agree that the current state is not ideal.
To my knowledge, you have the choice between "magic" string manipulation
(various ways) and "semantic" reflection (e.g. `$r = new
\ReflectionClass($fqcn);` -- which may try to autoload the class and throws
if it doesn't actually exist -- then use `$r->getNamespaceName()` and/or
`$r->getShortName()`).
Like `str_contains()` was introduced as a "shorthand" for `false !==
strpos()`, something like `get_namespace_name()` and/or `get_short_name()`
(or other namings) might be worth considering.

Regards,

-- 
Guilliam Xavier

Reply via email to