# [RFC] "use global functions/consts" statement

- Thread: https://externals.io/message/107953
- Original archive: https://news-web.php.net/php.internals/107953
- Started by tyson andre on 2020-01-01T19:31:05+00:00
- Messages: 45
- RFC: declare(function_and_const_lookup=global) (Declined) — https://externals.io/rfc/use_global_elements.md
- Page 1 of 2: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/107953.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #107953 — tyson andre — 2020-01-01T19:31:05+00:00

URL: https://externals.io/message/107953#107953

Hi internals,

This RFC proposes to support an opt-in "use global functions/consts;" statement to disable PHP's check for the function/const in the current namespace before falling back to the global namespace.

https://wiki.php.net/rfc/use_global_elements

Earlier discussion can be found in the 'Opt-in "use function *;" for skipping check for function/const in alternate namespace' email thread, which can be seen at https://externals.io/message/107877

Let me know if you have any comments on the RFC, e.g.
- Typical RFC feedback
- Missing parts, sections, or formatting issues in the RFC
- Choices of voting options
- Alternate syntax ideas ("use function *" was mentioned earlier, "use global function" doesn't make sense to me because it's singular instead of plural)
   e.g. different directive names for the declare() voting option.

Thanks,
- Tyson

---

## #107954 — Gabriel Caruso — 2020-01-01T20:30:23+00:00

URL: https://externals.io/message/107953#107954 · In reply to: #107953

Hello Tyson,



> Hi internals,
>
> This RFC proposes to support an opt-in "use global functions/consts;"
> statement to disable PHP's check for the function/const in the current
> namespace before falling back to the global namespace.
>
> https://wiki.php.net/rfc/use_global_elements
>
> Earlier discussion can be found in the 'Opt-in "use function *;" for
> skipping check for function/const in alternate namespace' email thread,
> which can be seen at https://externals.io/message/107877
>
> Let me know if you have any comments on the RFC, e.g.
> - Typical RFC feedback
> - Missing parts, sections, or formatting issues in the RFC
> - Choices of voting options
> - Alternate syntax ideas ("use function *" was mentioned earlier, "use
> global function" doesn't make sense to me because it's singular instead of
> plural)
>    e.g. different directive names for the declare() voting option.
>
> Thanks,
> - Tyson
> --
> 
> 


Do you have plans to use the https://github.com/php/php-rfcs to promote the
discussion as well, the same way we did
<https://github.com/php/php-rfcs/pull/1> for the Typed Properties RFC?

Best regards,

---

## #107955 — tyson andre — 2020-01-02T01:37:45+00:00

URL: https://externals.io/message/107953#107955 · In reply to: #107954

> Do you have plans to use the https://github.com/php/php-rfcs to promote the discussion as well, the same way
we did https://github.com/php/php-rfcs/pull/1 for the Typed Properties RFC?

No, I have no plans to switch to GitHub. At the time of writing, https://github.com/php/php-rfcs/blob/master/README.md has the following note about not submitting PRs, so I decided against trying out the experimental RFC process.

> This is just a one-off experiment for now, we'll have to discuss whether we want to move the RFC process towards this separately. *This repository may be abandoned. Please don't submit PRs for now.*

1. I'm not sure if there's a consensus on https://externals.io/message/107747#107747 ("GitHub RFC workflow").
2. I expect this RFC to be smaller in scope (of discussion) than adding union types to the language.

Other thoughts on "GitHub RFC workflow" (Sorry for this being off topic- I don't know how to reply to a mailing list thread I don't have in my inbox while preserving threading, from Outlook in a browser. The "In Reply To" header seems like what I'd want, but is impractical to set with this setup):

- It seems slightly time consuming and error-prone for formatting (but doable) to migrate from markdown to dokuwiki after the RFC is reviewed on GitHub (I see this was already mentioned). Maybe publishing the dokuwiki markup as plain text, linking to the wiki, and having code review on that would be a better option to write (but harder for reviewers unfamiliar with the dokuwiki format).
  Tooling (use pandoc or something else to convert from HTML (rendered by wiki) to markdown for the github PR) may help with that process - I'm not familiar with the best options. dokuwiki only has official support for export to odt and xhtml, as far as I can tell
- If I linked to a GitHub PR as a secondary source of reviews to the email thread (instead of the main source), it might be splitting up the discussion, and reviewers would miss or duplicate comments.

Thanks,
- Tyson

---

## #107956 — Mark Randall — 2020-01-02T04:31:48+00:00

URL: https://externals.io/message/107953#107956 · In reply to: #107953

> This RFC proposes to support an opt-in "use global functions/consts;" statement to disable PHP's check for the function/const in the current namespace before falling back to the global namespace.

It's an interesting idea, but at this time I think it's the wrong 
approach to what is in the best long-term interests of the language by 
introducing an additional point of inconsistency.

Classes search the current namespace, but functions / const would search 
namespace first, unless they don't, then global?

For the very minor one-time performance hit (thanks to the cache slot), 
I think the situation is best remaining as-is for the time being.

In future, I think the optimal solution is opt-in deprecating fallback 
to the root namespace using a declare. We might eventually benefit from 
versioned "libraries" of functions that can be imported in one command 
which would solve many-a-future-problem by itself.

Somewhat related is how global functions are consumed -

Id like to see nikic/scalar_objects added to the core in 8.0, that would 
offer non-procedural (and therefore non-namespaced) access to many of 
the most common global functions (strings, arrays etc). In turn, that 
would allow developers to limit the number of use \... statements.

That doesn't cover defined constants, but IMO we should be pushing those 
to be moved into class constants, simply because in the absense of 
function / constant / anything-but-class level autoloading, things might 
as well be in a readily available location.

--
Mark Randall
marandall@php.net

---

## #107957 — tyson andre — 2020-01-02T05:37:21+00:00

URL: https://externals.io/message/107953#107957

> It's an interesting idea, but at this time I think it's the wrong 
> approach to what is in the best long-term interests of the language by 
> introducing an additional point of inconsistency.
> 
> Classes search the current namespace, but functions / const would search 
> namespace first, unless they don't, then global?

Assuming you mean "unless they don't" is the additional inconsistency:

I still see this as a cleaner/less verbose option than the currently available options
for avoiding ambiguity - aliases add similar resolution behavior.

"function_name() will search the current namespace first,
then the global namespace,
unless "use function [.... as] function_name" was found
earlier in the namespace block."

> For the very minor one-time performance hit (thanks to the cache slot), 
> I think the situation is best remaining as-is for the time being.

That was unintuitive to me -- but it is one-time.
(ignoring optimizations of specialized opcodes
and inlining results as constants)
Running the following example outputs "Length is 4" twice.

<?php
namespace NSTest;
function computeStrlen() {
    printf("Length is %s\n", strlen("test"));
}
computeStrlen();
require 'b.php';
computeStrlen();
// contents of b.php
<?php
namespace NSTest;
function strlen($x) {
    return -1;
}

> In future, I think the optimal solution is opt-in deprecating fallback 
> to the root namespace using a declare.
> ... Id like to see nikic/scalar_objects added to the core in 8.0

Various global functions (strlen(), `count()`, `class_exists()`, `is_string()`, etc.)
are more frequently used than namespaced functions in many files,
and removing the fallback *to* the global scope would break most third party code,
which might be unmaintained.
This backwards compatibility break would discourage upgrading
to future major versions.

> That doesn't cover defined constants, but IMO we should be pushing those 
> to be moved into class constants, simply because in the absense of 
> function / constant / anything-but-class level autoloading, things might 
> as well be in a readily available location.

Out of scope of this RFC: I had a thought today about autoloading.
I'd rather improve function / const autoloading instead of moving to classes. 
What if an ambiguous function_name() or const outside the global 
namespace would attempt to autoload *ambiguous* functions in the global scope,
but not the current namespace?
(and autoload unambiguous functions in their respective scope) `function_exists()` or `defined()` would not autoload,
to preserve the behavior/performance of current programs.
Anything with the callable type hint (e.g. array_map) would also need to be modified.

- Same for global constants
- That should avoid the performance hit - this autoloading would only be triggered
  when php would previously throw an Error or warning
  for undefined functions/constants.
- This would also avoid the need to load polyfill files (e.g. mbstring)
  or test framework files when their functions/constants are unused.
- The main blocker for other autoload proposals
  seemed to be performance if I understood correctly
  (e.g. attempting to autoload NS\strlen() every time strlen was called)

Fully-qualified calls (through use, \, or being in the global scope) would
autoload the unambiguous name for missing functions.

And there'd have to be a hash map or other check
to avoid recursion on the same constant/function.

---

## #107959 — Rowan Tommins — 2020-01-02T12:32:58+00:00

URL: https://externals.io/message/107953#107959 · In reply to: #107957

> Out of scope of this RFC: I had a thought today about autoloading.
> I'd rather improve function / const autoloading instead of moving to
> classes.
> What if an ambiguous function_name() or const outside the global
> namespace would attempt to autoload *ambiguous* functions in the global
> scope,
> but not the current namespace?
> (and autoload unambiguous functions in their respective scope)
>


Could you expand on what you mean by "ambiguous" / "unambiguous" here?

I think any nuance to which function is autoloaded needs to match the
actual name resolution - it wouldn't make much sense for some_function() to
call CurrentNS\some_function if already defined, but trigger an autoloader
for \some_function if not. There may be simplifications with the proposed
directive from this RFC, but we'd need to think through the different
combinations and make sure they behaved consistently and intuitively.

Regards,
-- 
Rowan Tommins
[IMSoP]

---

## #107960 — Mike Schinkel — 2020-01-02T16:52:43+00:00

URL: https://externals.io/message/107953#107960

> 
> In future, I think the optimal solution is opt-in deprecating fallback to the root namespace using a declare. We might eventually benefit from versioned "libraries" of functions that can be imported in one command which would solve many-a-future-problem by itself.

+1 to that.  

Especially if there is a mechanism to define functions from other people's code to be included in those "libraries", such as the functions in the WordPress API.

> Id like to see nikic/scalar_objects added to the core in 8.0, that would offer non-procedural (and therefore non-namespaced) access to many of the most common global functions (strings, arrays etc). In turn, that would allow developers to limit the number of use \... statements.

And +1000 to that!

-Mike

---

## #107962 — tyson andre — 2020-01-02T18:14:43+00:00

URL: https://externals.io/message/107953#107962 · In reply to: #107960

> We might eventually benefit from versioned "libraries" of functions that can be imported in one command
> which would solve many-a-future-problem by itself.

I'd be in favor of a module system, I just can't think of a good way to migrate to that with existing limitations.
I'd imagine there would be various obstacles/objections to getting an RFC for that approach accepted.

Of course, whatever you're thinking of for "libraries" might
be completely different than what I think you mean.
Proposals for that could start a different thread.

For example, if one wanted a module system like NodeJS with "import functions, consts from 'some_native_module_or_php_file'"/"export function ..."

1. Languages such as NodeJS, Python, etc. still have a core set of functions that get loaded even if there are no imports.
    Those functions can get added to dynamically (see note on polyfills.
    https://stackoverflow.com/questions/27930038/how-to-define-global-function-in-python is hopefully rare)
    That would be an argument in favor of preferring deprecating checking in the current namespace,
    not deprecating the global namespace. (for uses that aren't fully qualified)
2. It's possible for almost any php module's functionality such as "mbstring" to be provided by a native module,
   or from a pure php polyfill such as symfony/mbstring-polyfill. https://www.php.net/mbstring
   Or even just a few functions from an extension.
   I don't know how the equivalent of "import [functions, consts] from 'mbstring'" would work in a portable way,
   e.g. with a future version of the composer autoloader.
3. This would add more ambiguity if imported names can get overridden (e.g. by MyNs\strlen),
   making opcache less beneficial to performance.
   It would also make it harder to comprehend code if exported functions from modules can have aliased names.

A more limited version of "libraries" might be possible (pure php only with other limitations) but it doesn't seem as useful.

---

## #107968 — tyson andre — 2020-01-03T01:58:22+00:00

URL: https://externals.io/message/107953#107968 · In reply to: #107959

> Could you expand on what you mean by "ambiguous" / "unambiguous" here?

I started the thread "Autoloading functions/consts without a performance impact"
for any other discussion on autoloading. It clarifies what "ambiguous" means.
In my earlier comments, I didn't realize https://wiki.php.net/rfc/autofunc was already created
and is similar to what I had in mind,
but as far as I know never had a proof of concept to vote on.

---

## #108127 — tyson andre — 2020-01-14T18:27:27+00:00

URL: https://externals.io/message/107953#108127 · In reply to: #107953

> This RFC proposes to support an opt-in "use global functions/consts;" statement
> to disable PHP's check for the function/const in the current namespace before falling back to the global namespace.
> 
> https://wiki.php.net/rfc/use_global_elements
> 
> 
> Earlier discussion can be found in the 'Opt-in "use function *;" for skipping check for
> function/const in alternate namespace' email thread, which can be seen at
https://externals.io/message/107877
>Let me know if you have any comments on the RFC

I plan to update the wiki and start the voting phase tomorrow with the voting structure mentioned in https://wiki.php.net/rfc/use_global_elements
Alternatives/Arguments mentioned in this thread have had summaries added in the discussion section.

Thanks,

- Tyson

---

## #108132 — Nikita Popov — 2020-01-14T21:51:58+00:00

URL: https://externals.io/message/107953#108132 · In reply to: #108127

On Tue, Jan 14, 2020 at 7:27 PM tyson andre <tysonandre775@hotmail.com>
wrote:

> > […]
> statement
> > […]
> before falling back to the global namespace.
> > […]
> skipping check for
> > […]
> https://externals.io/message/107877
> > […]
>
> I plan to update the wiki and start the voting phase tomorrow with the
> voting structure mentioned in https://wiki.php.net/rfc/use_global_elements
> Alternatives/Arguments
> <https://wiki.php.net/rfc/use_global_elementsAlternatives/Arguments>
> mentioned in this thread have had summaries added in the discussion section.
>

Hi Tyson,

I don't think it's a good idea to resolve the question of "use global
functions" vs "declare" as a subsidiary vote. At least in my mind, those
two options are significantly different, and this choice would affect both
my overall opinion of the proposal and also the answer I would give on some
of the other voted question.

The RFC already outlines a number of reasons why it is preferable to
implement this as a declare directive, so please excuse my reiterating some
points here :)

First and foremost, if we ever implement
https://wiki.php.net/rfc/namespace_scoped_declares or some similar way of
specifying declares on the package level, and I think it's pretty likely
that we're going to do this in one form or another, then we're very much
going to regret not making this a declare. Disabling the namespace
fallback, just like the use of strict types, is something you will usually
want to do for an entire library/project, not just for individual files.
Going for something like "use global functions" preemptively precludes this
for no good reason.

Second, I think phrasing the semantics in terms of a change to name
resolution behavior (which the declare does) is clearer than phrasing it as
"import all functions/consts in the global namespace". That's not really
what this this feature is doing on a technical level, and this phrasing is
what results in questions regarding the behavior for various conditions
regarding symbol overlaps etc. For example, with the declare, I don't think
that it should be an error to make a function declaration inside a
namespace -- that's still entirely well defined, and I think a legitimate
use-case (a project that is disabling namespace fallback everywhere, will
likely want to do that for files declaring functions as well, as a matter
of consistency.)

Third, I'm not sure it makes sense to separate this functionality for
functions and for constants. I can't really imagine a situation where you
would want to, say, use namespaced constants but global functions. I can
see why you went with this split when using the "use" syntax (as we already
have "use function" and "use const" both), but with a declare approach, I
would suggest to combine both. Functions and constants live in different
symbol spaces, but their name resolution behavior is the same.

Finally, if you do want to go with the "use" syntax, "functions" and
"consts" should not be made reserved keywords. There is no technical need
for these to be true keywords, so we can avoid an unnecessary BC break here.

Regards,
Nikita

---

## #108134 — tyson andre — 2020-01-15T00:14:22+00:00

URL: https://externals.io/message/107953#108134 · In reply to: #108132

I'll be postponing the vote to update the RFC and proof of concept/tests associated with it to use declare()

Also, "declare(lookup_functions_in_current_namespace = false, lookup_consts_in_global_namespace = false)" in the file's declare() blocks was my first idea.
Any ideas - declare(disable_ambiguous_element_lookups=1), declare(disable_ambiguous_lookups_in_current_namespace=1), etc?

x=1 seems to be more common, and reflects the fact that this is not the default.

> I don't think it's a good idea to resolve the question of "use global functions" vs "declare" as a subsidiary vote.
> At least in my mind, those two options are significantly different, and this choice would affect both my overall opinion of the proposal
> and also the answer I would give on some of the other voted question.

Agreed, I had some of those concerns after suggesting setting it up that way.
It doesn't capture "accept if one option, but not if the other option".


Ideally, I could have a vote for the syntax to use for the RFC,
then amend the RFC with the syntax, but that isn't practical.

> The RFC already outlines a number of reasons why it is preferable to implement this as a declare directive,
> so please excuse my reiterating some points here :)
> First and foremost, if we ever implement 
https://wiki.php.net/rfc/namespace_scoped_declares or some similar way of specifying declares on the package level,
> and I think it's pretty likely that we're going to do this in one form or another, then we're very much going to regret not making this a
 declare.
> Disabling the namespace fallback, just like the use of strict types, is something you will usually want to do for an entire library/project, not just for individual files.
> Going for something like "use global functions" preemptively precludes this for no good reason.

That's a good point. I think that's the first time I've seen that RFC.
https://wiki.php.net/rfc/namespace_scoped_declares#nesting_behavior / 
https://wiki.php.net/rfc/namespace_scoped_declares#implementation_considerations answers my questions about how that would work with readability/opcache.

It'd definitely be convenient to have less boilerplate.

> Second, I think phrasing the semantics in terms of a change to name resolution behavior (which the declare does)
> is clearer than phrasing it as "import all functions/consts in the global namespace".
> That's not really what this this feature is doing on a technical
 level, and this phrasing is what results in questions regarding the behavior for various conditions regarding symbol overlaps etc.
> For example, with the declare, I don't think that it should be an error to make a function declaration inside a namespace
> -- that's still entirely well defined, and I think a legitimate use-case
> (a project that is disabling namespace fallback everywhere, will likely want to do that for files declaring functions as well, as a matter of consistency.)

My concern was about this being well-defined but being likely to be accidentally misused, e.g. with namespace-scoped declares.
Same for NS\my_printf calling \my_sprintf instead of NS\my_sprintf within the same file.
Explicitly changing to namespace\my_sprintf() or uses would be one way to migrate code like that.

    namespace Example;
    use global functions;  // or declare()
    // interpreting this literally, without `use Example\fact;` instead of namespace\fact, this is calling \fact(), which is surprising
    // (the old equivalent `use function fact;` would throw because of the name reuse) 
    function fact($n) { return $n > 1 ? $n * fact($n - 1) : 1; }


> Third, I'm not sure it makes sense to separate this functionality for functions and for constants.
> I can't really imagine a situation where you would want to, say, use namespaced constants but global functions.
> I can see why you went with this split when using the "use" syntax (as we already have "use function" and "use const" both),
> but with a declare approach, I would suggest to combine both. Functions and constants live in different symbol spaces,
> but their name resolution behavior is the same.

If you're declaring a function or a constant in a namespace, the way I implemented it would throw an Error at compile time to avoid confusion.
If it didn't throw an Error, then I'd agree that it'd virtually always be used together, except possibly when migrating to being stricter gradually.

> Finally, if you do want to go with the "use" syntax, "functions" and "consts" should not be made reserved keywords.
> There is no technical need for these to be true keywords, so we can avoid an unnecessary BC break here.

Agreed for future work on "use"

---

## #108193 — tyson andre — 2020-01-18T18:05:35+00:00

URL: https://externals.io/message/107953#108193 · In reply to: #108134

Hi internals,

After feedback, the RFC syntax has been changed from `use global functions` to `declare(disable_ambiguous_element_lookup=1)`. In addition,

- The two settings have been combined into a single option,
  which is now declare(disable_ambiguous_element_lookup=1) at the top of a file.

  Those settings would be enabled together, in any use case I can think of.
- Declaring global functions and constants in files with declare(disable_ambiguous_element_lookup=1) is now allowed in any namespace,
  to allow code to continue to work even with future changes such as https://wiki.php.net/rfc/namespace_scoped_declares
  (and so that files declaring functions or constants can have consistent coding style with files that don't)
- The following voting choices have been removed: (1) the syntax and for (2) whether declaring functions/constants are errors

  The outcome of those votes would noticeably change the RFC and affect whether voters would vote for the RFC as a whole.

The RFC https://wiki.php.net/rfc/use_global_elements has been updated.
The implementation at https://github.com/php/php-src/pull/4951 has also been updated.

I was planning to move this to the voting stage on the 25th (1 week),
since the revised RFC is similar to the old RFC,
and arguments in favor of declare() have been mentioned for over 2 weeks.

Thanks,
- Tyson

---

## #108194 — Claude Pache — 2020-01-18T20:03:34+00:00

URL: https://externals.io/message/107953#108194 · In reply to: #108193

Hi,

I find that the “disable_ambiguous_element_lookup” directive name is, well, ambiguous. Does it mean that it will look up only in the current namespace, or only in the global namespace? I can’t guess.

Maybe a three-value directive:

	declare(function_and_const_lookup=global);
	declare(function_and_const_lookup=namespace);
	declare(function_and_const_lookup=fallback); // the default

—Claude

---

## #108195 — Mark Randall — 2020-01-18T21:32:07+00:00

URL: https://externals.io/message/107953#108195 · In reply to: #108193

>    which is now declare(disable_ambiguous_element_lookup=1) at the top of a file.

I_suspect_these_long_declares_might_get_tedious

Can we at least agree on internals that a declare doesn't have to have a 
negative default value that is toggled on?

I'd much rather have something like:

declare(ambiguous_element_lookup=0)
declare(ambiguous_element_lookup=off)

--
Mark Randall
marandall@php.net

---

## #108196 — Olumide Samson — 2020-01-18T21:42:01+00:00

URL: https://externals.io/message/107953#108196

"namespace_lookup"



> 
> > […]
> of a file.
>
> I_suspect_these_long_declares_might_get_tedious
>
> Can we at least agree on internals that a declare doesn't have to have a
> negative default value that is toggled on?
>
> I'd much rather have something like:
>
> declare(ambiguous_element_lookup=0)
> declare(ambiguous_element_lookup=off)
>
> --
> Mark Randall
> marandall@php.net

---

## #108197 — tyson andre — 2020-01-18T22:53:22+00:00

URL: https://externals.io/message/107953#108197

> I'd much rather have something like:
>
> declare(ambiguous_element_lookup=0)
> 
> declare(ambiguous_element_lookup=off)

Aside: declare(unambiguous_element_lookup=1) is probably a better choice than my first choice of (disable_ambiguous_element_lookup=1), but probably not the best choice.

> I find that the “disable_ambiguous_element_lookup” directive name is, well, ambiguous.
> Does it mean that it will look up only in the current namespace, or only in the global namespace? I can’t guess.
> 
> Maybe a three-value directive:
> 
>    declare(function_and_const_lookup=global);
>    declare(function_and_const_lookup=namespace);
>    declare(function_and_const_lookup=fallback); // the default

That's my favorite setting name overall so far - it ends up being as long as disable_ambiguous_element_lookup and more self-explanatory.
I don't plan to include namespace-only in the RFC - future RFCs could propose additional values independently.

Probably just `= global` and `= default`, because the default might eventually change (from the fallback),
and = fallback could be added if the old fallback was desirable enough.
- `= default` would only be useful to set resolution back to the default
  with future language changes such as https://wiki.php.net/rfc/namespace_scoped_declares#implementation_considerations

> "namespace_lookup"

It might cause confusion when a new php programmer tries to set this setting,
and discovers that catch(Exception) {} still means MyNS\Exception with declare(namespace_lookup=global).
(assuming you meant something along those lines)

---

## #108228 — Nikita Popov — 2020-01-24T16:00:06+00:00

URL: https://externals.io/message/107953#108228 · In reply to: #108197

On Sat, Jan 18, 2020 at 11:53 PM tyson andre <tysonandre775@hotmail.com>
wrote:

> > […]
>
> Aside: declare(unambiguous_element_lookup=1) is probably a better choice
> than my first choice of (disable_ambiguous_element_lookup=1), but probably
> not the best choice.
>
> > […]
> well, ambiguous.
> > […]
> in the global namespace? I can’t guess.
> > […]
>
> That's my favorite setting name overall so far - it ends up being as long
> as disable_ambiguous_element_lookup and more self-explanatory.
> I don't plan to include namespace-only in the RFC - future RFCs could
> propose additional values independently.
>
> Probably just `= global` and `= default`, because the default might
> eventually change (from the fallback),
> and = fallback could be added if the old fallback was desirable enough.
> - `= default` would only be useful to set resolution back to the default
>   with future language changes such as
> https://wiki.php.net/rfc/namespace_scoped_declares#implementation_considerations
>

It looks like the implementation has been updated to the style proposed
here, while the RFC still uses disable_ambiguous_element_lookup.

I like the idea of using a meaningful value here, but think that this
should be using a string, i.e. declare(function_and_const_lookup='global')
rather than declare(function_and_const_lookup=global). Currently declare()
syntax uses a normal constant expression on the right hand side of the =,
and I don't see a strong reason why we should deviate from that for this
feature. An existing declare using a string is declare(encoding='UTF-8').

The RFC says:

function sprintf($msg, ...$args) {
    // this and remaining statements still refer to \sprintf, not
MyNS\sprintf
    return sprintf("Prefix $msg", ...$args);
}

This looks a bit peculiar... We could also say that declaring a symbol also
automatically brings it into scope. I'm not really sure which is better.

As a general note on the overall proposal: I think this is a very pragmatic
proposal. It addresses a real issue, and it addresses it in the most
straightforward way. You can just drop the declare in your code, and it
will keep working exactly as it did before, just faster. Assuming you
weren't doing anything stupid, of course.

The big downside is that this makes class and function symbol resolution
complete opposites. Classes only look in the current namespace. Functions
only look in the global namespace. This reflects the way they are most
commonly used, but is not a great place to end up from a language design
perspective.

There are two alternatives that keep class and function symbol resolution
the same: One is to always only look in the namespace. This has been
suggested a few times in the past, including in this thread, and the RFC
https://wiki.php.net/rfc/fallback-to-root-scope-deprecation. I think this
is a fairly unpopular option, because using fully qualified names for
functions tends to be quite ugly (more so than for classes, due to the
positions they're used in), or requires a large number of imports, as even
a small piece of code can easily use a dozen different string/array
functions.

One option that I haven't seem much discussion on is the opposite: Always
only look in the global namespace. Any unimported unqualified usages will
be treated as fully qualified names. This would match the proposed
semantics for functions/consts and change the resolution rules for classes.
I think this would have relatively little impact on how code is written, as
classes already tend to make extensive use of cross-namespace references
and the import is usually IDE managed.

Regards,
Nikita

---

## #108229 — Nicolas Grekas — 2020-01-24T16:10:18+00:00

URL: https://externals.io/message/107953#108229 · In reply to: #108228

> One option that I haven't seem much discussion on is the opposite: Always
> only look in the global namespace. Any unimported unqualified usages will
> be treated as fully qualified names. This would match the proposed
> semantics for functions/consts and change the resolution rules for classes.
> I think this would have relatively little impact on how code is written, as
> classes already tend to make extensive use of cross-namespace references
> and the import is usually IDE managed.
>


Quick reaction: that'd make sense to me!

Adding a "use CurrentNamespace\Foo" or using "namespace\Foo" looks easy
enough to adopt.
Does this mean you're suggesting to use declare(symbol_lookup='global')? Or
shorter: declare(lookup='global'), or maybe even declare(global_lookup=1)
as I'm not sure we need 3 options here?

---

## #108230 — tyson andre — 2020-01-24T17:58:50+00:00

URL: https://externals.io/message/107953#108230 · In reply to: #108229

> > […]
> only look in the global namespace. Any unimported unqualified usages will
> > […]
> 
> Quick reaction: that'd make sense to me!
> 
> Adding a "use CurrentNamespace\Foo" or using "namespace\Foo" looks easy enough to adopt.
> Does this mean you're suggesting to use 
> declare(symbol_lookup='global')? Or shorter: declare(lookup='global'), or
> maybe even declare(global_lookup=1) as I'm not sure we need 3 options here?

The RFC has been updated after feedback, but I forgot to update the wiki and PR title.

I sent out an email last week mentioning that https://wiki.php.net/rfc/use_global_elements
is now a single `declare()` setting `declare(function_and_const_lookup=global)`

> Always only look in the global namespace.

Other RFCs have proposed that approach.
I mentioned the objections others had to that RFC in
https://wiki.php.net/rfc/use_global_elements#deprecate_the_fallback_to_the_root_namespace_instead

"Deprecating the behavior of existing code would break (possibly unmaintained) third-party libraries
and require a lot of code changes, discouraging updates to the latest version of PHP."

> I like the idea of using a meaningful value here, but think that this
> should be using a string, i.e. declare(function_and_const_lookup='global')
> rather than declare(function_and_const_lookup=global). Currently declare()
> syntax uses a normal constant expression on the right hand side of the =,
> and I don't see a strong reason why we should deviate from that for this
> feature. An existing declare using a string is declare(encoding='UTF-8').

Whether it's quoted is a low priority to me - I went with the unquoted implementation
because it might be something repeated in every file of a project,
and it'd be slightly more convenient to avoid quotes and use keywords if there were
many more settings with different values (=on, =off, =warning, etc) in the future.
A difference is that it makes sense to quote encodings such as UTF-8 because of the '-',
but not as much to quote keywords without special characters.

> It looks like the implementation has been updated to the style proposed
> here, while the RFC still uses disable_ambiguous_element_lookup.

Fixed, forgot to update the wiki after updating the implementation

---

## #108231 — tyson andre — 2020-01-24T18:11:29+00:00

URL: https://externals.io/message/107953#108231 · In reply to: #108228

> I like the idea of using a meaningful value here, but think that this
> should be using a string, i.e. declare(function_and_const_lookup='global')
> rather than declare(function_and_const_lookup=global). 

Also, I could make that a voting option, and it could be changed before 8.0 alphas if new concerns come up after a vote.

> This looks a bit peculiar... We could also say that declaring a symbol also automatically brings it into scope.
> I'm not really sure which is better.

Neither am I. There were edge cases with doing that that may cause more confusion

    namespace NS;
    function f() { /* calls g() - which g() */ }
    function g() { /* calls f() */ }

    if (!function_exists('NS\h')) {
        function h() {}
    } else {
        // what will h() refer to
    } 
    // what will h() refer to

> As a general note on the overall proposal: I think this is a very pragmatic proposal. It addresses a real issue, and it addresses it in the most straightforward way. You can just drop the declare in your code, and it will keep working exactly as it did
> before, just faster. Assuming you weren't doing anything stupid, of course.
>
> The big downside is that this makes class and function symbol resolution complete opposites. Classes only look in the current namespace. Functions only look in the global namespace. This reflects the way they are most commonly used, but is not a great
 place to end up from a language design perspective.
>
There are two alternatives that keep class and function symbol resolution the same: One is to always only look in the namespace. This has been suggested a few times in the past, including in this thread, and the RFC
https://wiki.php.net/rfc/fallback-to-root-scope-deprecation. I think this is a fairly unpopular option, because using fully qualified names for functions tends to be quite ugly (more
 so than for classes, due to the positions they're used in), or requires a large number of imports, as even a small piece of code can easily use a dozen different string/array functions.

Agreed

> One option that I haven't seem much discussion on is the opposite: Always only look in the global namespace. Any unimported unqualified usages will be treated as fully qualified names.
> This would match the proposed semantics for functions/consts and change
 the resolution rules for classes.
> I think this would have relatively little impact on how code is written, as classes already tend to make extensive use of cross-namespace references and the import is usually IDE managed.

Also, about the note on classes.

It's fairly common for NS\SubNS\ClassName to mention other classes from NS\SubNS\OtherClassName right now,
(more commonly than use Exception, use Throwable, etc in some cases),
and changing that default would require changing a lot of third party code.
A separate option such as `declare(lookup_classes=global)` would allow migrating to that,
but would confuse developers switching between codebases using different settings of lookup_classes,
and introduce similar confusion about the rare case of multiple classes in one file.

---

## #108250 — Nikita Popov — 2020-01-26T10:08:56+00:00

URL: https://externals.io/message/107953#108250 · In reply to: #108230

On Fri, Jan 24, 2020 at 6:58 PM tyson andre <tysonandre775@hotmail.com>
wrote:

> > […]
> declare(function_and_const_lookup='global')
> > […]
> declare()
> > […]
>
> Whether it's quoted is a low priority to me - I went with the unquoted
> implementation
> because it might be something repeated in every file of a project,
> and it'd be slightly more convenient to avoid quotes and use keywords if
> there were
> many more settings with different values (=on, =off, =warning, etc) in the
> future.
> A difference is that it makes sense to quote encodings such as UTF-8
> because of the '-',
> but not as much to quote keywords without special characters.
>

Saving two characters per file doesn't seem like a great motivation to add
additional special cases to core language syntax. Right now, declare just
types "identifier = expr", while with this change it's going to be
"identifier = (expr | a | few | extra | keywords)".

> > […]
Always only look in the global namespace. Any unimported unqualified usages
will be treated as fully qualified names.
> > […]
the resolution rules for classes.
> > […]
written, as classes already tend to make extensive use of cross-namespace
references and the import is usually IDE managed.
>
> It's fairly common for NS\SubNS\ClassName to mention other classes from
NS\SubNS\OtherClassName right now,
> (more commonly than use Exception, use Throwable, etc in some cases),

Out of interest, I checked how the symbol reference distribution in
open-source projects look like. These numbers are for unique class name
references inside namespaces:

Global: int(88398)
Same namespace: int(83790)
Other namespace: int(315455)

So, most references are to classes outside the current namespace. The
number of references to global classes and classes in the same namespace is
actually pretty similar, there are 5% more global references.

From that perspective, changing the name resolution rules to always look
for the global symbol if unimported would actually slightly reduce the
number of necessary "use" statements.

> and changing that default would require changing a lot of third party
code.
> A separate option such as `declare(lookup_classes=global)` would allow
migrating to that,
> but would confuse developers switching between codebases using different
settings of lookup_classes,
> and introduce similar confusion about the rare case of multiple classes
in one file.

If we were to make such a change (hypothetically), the way I would view it
is "use new name resolution rules" or not, rather than a collection of
fine-grained options. Notably Rust made a major change to how symbols are
resolved in the 2018 edition, so such things aren't inconceivable,
especially with the right tooling.

Nikita

---

## #108251 — tyson andre — 2020-01-26T16:25:29+00:00

URL: https://externals.io/message/107953#108251 · In reply to: #108250

Hi internals,

https://wiki.php.net/rfc/use_global_elements and the implementation has been updated again - the syntax is now declare(function_and_const_lookup='global')
with a literal string instead of a keyword.
The voting option for whether it was a string or a keyword was removed.

I plan to move this to the voting phase on Monday, if nothing else needs to be addressed

> Saving two characters per file doesn't seem like a great motivation to add additional special cases to core language syntax.
> Right now, declare just types "identifier = expr", while with this change it's going to be "identifier = (expr | a | few | extra | keywords)".

Thinking about it again, I'd agree with the parsing special cases being inconvenient.

> So, most references are to classes outside the current namespace. The number of references to global classes and classes in the same namespace is actually pretty similar, there are 5% more global references.
> From that perspective, changing the name resolution rules to always look for the global symbol if unimported would actually slightly reduce the number of necessary "use" statements.

It would be more understandable for new php developers familiar with other languages if name lookup was consistent across classes.

I don't have as strong a use case for this as I do for eliminating the function/const ambiguity. Changing class resolution (via automated tool) would require more code changes than function/constant resolution, and the classes are already unambiguous.

> If we were to make such a change (hypothetically), the way I would view it is "use new name resolution rules" or not, rather than a collection of fine-grained options.
> Notably Rust made a major change to how symbols are
> resolved in the 2018 edition, so
> such things aren't inconceivable, especially with the right tooling.

If a setting affecting all name resolution was added, then forbidding the use of both that new setting (e.g. <name_lookup=global>) and declare(function_and_const_lookup) in the same file would keep code simpler.

If "use new name resolution rules" was the only option, the larger amount of refactoring for class references (and doc comments) might discourage using the new name resolution for functions/constants, and make backporting patches to previous major versions of applications/libraries more error prone (e.g. \MyNS\Exception vs \Exception). The refactoring might also be perceived as risky.
So I'd still want to see the voting results&feedback for function_and_const_lookup before investigating approaches to changing class resolution.

Rust would also catch many more possible bugs in symbol resolution at compile time.
The static analyzers for PHP can detect almost as many bugs, but would require that people be aware of the analyzers, configure them, and use them in CI.

- Code such as if (class_exists(SomeClass::class)) { /* Use SomeClass */ } might be permitted if analyzing class_exists conditionals is a feature of a static analyzer.

- Tyson

---

## #108252 — Claude Pache — 2020-01-26T20:32:35+00:00

URL: https://externals.io/message/107953#108252 · In reply to: #108251

Hi,

I object to the following proposed behaviour, which is confusing:

<?php
declare(function_and_const_lookup='global');
 
namespace MyNS;
 
function sprintf($msg, ...$args) {
    // this and remaining statements still refer to \sprintf, not MyNS\sprintf
    return sprintf("Prefix $msg", ...$args);
}
?>

I think we can do better, following the example of what we have today, namely: Currently, the following triggers a fatal error:

<?php
namespace MyNS;
use function OtherNS\foo;

function foo() { }
// Fatal Error: Cannot declare function MyNS\foo because the name is already in use
?>

Therefore I suggest that the following be an error:

<?php
declare(function_and_const_lookup='global');
namespace MyNS;

function foo() { }
// Fatal Error: Cannot declare function foo because the name refers is in the global namespace

?>

and that you have to explicitly say that you use the current namespace for that name:

<?php
declare(function_and_const_lookup='global');
namespace MyNS;
use function MyNS\foo;
// or, equivalently: use function namespace\foo:

function foo() { }

foo(); // <-- this is the function defined just above

?>

—Claude

---

## #108254 — tyson andre — 2020-01-26T21:37:26+00:00

URL: https://externals.io/message/107953#108254 · In reply to: #108252

> and that you have to explicitly say that you use the current namespace for that name:
> 
> <?php
> declare(function_and_const_lookup='global');
> namespace MyNS;
> use function MyNS\foo;
> // or, equivalently: use function namespace\foo:
>
> function foo() { }
>
> foo(); // <-- this is the function defined just above

That's a good solution to the ambiguity that I hadn't considered. Functions and constants should be relatively uncommon for most projects, although I can see it getting repetitive for a file with dozens of constants.
(e.g. with namespace-scoped declares) `define()` or declare(function_and_const_lookup='global') should be adequate workarounds.
- A subsequent RFC could reduce the restriction and make "const X = ..." always act as though it was immediately preceded by "use const X"
  This works better for constants than functions because constants can't be declared anywhere but the top level.

`use function namespace\foo;` is a syntax error, though. It can only be used as `namespace\foo();`. It may be useful to add if projects adopt function_and_const_lookup, or other changes to namespace resolution get made.

- Tyson

---

Next page: https://externals.io/message/107953.md?page=2
