> The one part of the RFC that surprised me was this: > > > When getting the name of constants and functions, the name will NOT be the > > full name, but the lexical name. This means that if the name is use'd, it > > will be that name. However, if the full name is used in the nameof(), the > > full name is returned. > > No reason is given *why* it works this way, and expanding the namespaces on a > name is one of the most useful features of "::class". Importantly, it means > that the string created can be passed to other contexts, and still refer to > the same thing. For instance:
I'll update the RFC for the reasoning later tonight, but it's actually a pretty simple one. There are other languages that have something similar (C# and Scala, from personal experience) and usually, they provide an unqualified name. This can be annoying, for exactly the reason you describe: when you want to pass the value to another context. Most of the time, you want the unqualified name, but then there are times you want the qualified name, and getting it can be a complex process. By allowing developers to provide a fully qualified name, if that is what they want, developers have more control over their experience. This is especially important when using traits and aliases: trait A { public function example() {} } trait B { public function example() {} } class C { use A, B { A::example insteadof B; B::example as exampleB; } } $a = new C(); echo nameof($a->exampleB(...)); // outputs: "exampleB" The actual 'qualified name' is "example" or maybe "B::example" but that isn't very helpful if you want to call $a->B::example instead of $a->A::example later on. Or consider if you have an aliased const: namespace A { const A = 1; } namespace B { use const A\A as TEST; echo nameof(TEST); } In this case, if you want to use nameof(TEST) in an error message or something else, it would be surprising to get \A\A instead of TEST. So, for your example, we can instead call nameof(\Acme\bar(...)) instead of the aliased name when passing to another context: use function Acme\bar as foo; ... #[SomeAttribute(callback: nameof(\Acme\bar(...))] ... I hope this helps! > Similarly, I'm not wholly clear why nameof(MyClass::method(...)) should > evaluate to "method" rather than "MyClass::method" or indeed > "Full\NamespaceOf\MyClass::method". Usually, you want the name of the 'last' thing". For example, if you want the name of a property called "myProperty", using nameof($this->myProperty), you probably just want "myProperty" and not "{some_internal_instance_id}->myProperty" that you have to parse to really use. Instead, we can compse ::class and/or nameof() to achieve the same thing if we want to. -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php