Re: [Concept] Flip relative function lookup order (global, then local)

From: Date: Fri, 23 Aug 2024 11:28:13 +0000
Subject: Re: [Concept] Flip relative function lookup order (global, then local)
References: 1 2  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On Fri, 23 Aug 2024, at 10:58, Stephen Reay wrote:
> In a world where global functions take precedence over local ones 
> because some people don't like writing a single \ character, 
> autoloading would be a moot point because if you preference global 
> functions you're implicitly telling developers they shouldn't write 
> namespaced functions, by making them harder and less intuitive to use.

Sorry to reply to the same message twice, but as a concrete example, consider this code:

// Definition
namespace Acme\Foo;
class Utils {
    public static function magic(string $x): int {
        return \strlen($x);
    }
    public static function more_magic(string $x): int {
         return self::magic($x) * 2;
    }
}

// Caller
namespace Acme\MyApp\SearchPage;
use Acme\Foo\Utils;
echo Utils::more_magic($_GET['query']);


Rewritten as namespaced functions, with current PHP:

// Definition
namespace Acme\Foo\Utils;
function magic(string $x): int {
     return strlen($x);
}
function more_magic(string $x): int {
      return magic($x) * 2;
}

// Caller
namespace Acme\MyApp\SearchPage;
use Acme\Foo\Utils;
echo Utils\more_magic($_GET['query']);



With "unqualified names are global", but a new "_\" shorthand for "relative
to current", the caller is completely unaffected, but the definition becomes:

namespace Acme\Foo\Utils;
function magic(string $x): int {
     return strlen($x);
}
function more_magic(string $x): int {
      return _\magic($x) * 2;
}

Note how the "_\" is used in all the same places as "self::" was in the
"static class" version.

With "unqualified names are local", the change is very similar, but "the other way
around":

namespace Acme\Foo\Utils;
function magic(string $x): int {
     return \strlen($x);
}
function more_magic(string $x): int {
      return magic($x) * 2;
}

Regards,
-- 
Rowan Tommins
[IMSoP]


Thread (112 messages)

« previous php.internals (#125122) next »