Re: [RFC] class_name:namespace

From: Date: Fri, 26 Feb 2021 11:23:53 +0000
Subject: Re: [RFC] class_name:namespace
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-113284@lists.php.net to get a copy of this message


> Le 26 févr. 2021 à 09:16, Manuel Canga <php@manuelcanga.dev> a écrit :
> 
> Hello, another example with "factories method"[1]:
> 
> ```php
> use MyProject\Framework;
> 
> abstract class AbstractController {
>  private const HELPER_PATH = static::namespace.'/Helpers';
>  private const SERVICE_PATH = static::namespace.'/Services';
> 
>   public function instanceHelper( string $helperClass ) {
>          $helperClassName = self::HELPER_PATH."/{$helperClass}";
> 
>         return new $helperClassName();
>  }
> 
> public function instanceService( string $serviceClass )  {
>          $serviceClassName = self::SERVICE_PATH."/{$serviceClass}";
> 
>         return new $serviceClassName();
> }
> }
> 
> use MyProject\MyModule;
> 
> class Controller {
>  public function __invoke() {
>               //......
>     $date = $this->instanceHelper('Date');
>            //...
>  }
> 
> }
> ```
> 
> [1]: https://en.wikipedia.org/wiki/Factory_method_pattern
> 
> Regards
> --
> Manuel Canga
> 
> Zend Certified PHP Engineer 
> Websites: https://manuelcanga.dev | https://trasweb.net
> Linkedin: https://es.linkedin.com/in/manuelcanga
> 
> -- 
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php

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


Thread (16 messages)

« previous php.internals (#113284) next »