TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

PHP Type Alias

3 点作者 oladoyinbov超过 1 年前
i was kinda wondering maybe it&#x27;s worth it to write an RFC on PHP type alias. this will be really useful in the sense of maintenance, re-usability, readability and many more..<p>``` &lt;?php<p>type T = bool|int;<p>type Result = string;<p>function greeting(T $input): Result { return match() {<p><pre><code> true, 1 =&gt; &#x27;hello user :) &#x27;, false, 2 =&gt; &#x27;good-bye user&#x27; } </code></pre> }<p>```<p>What&#x27;s your opinion on this?

3 条评论

moritzwarhier超过 1 年前
Sounds great. But I supsect PHP had to make big tradeoffs for its checked-at-runtime types that would make this hard.<p>In contrast to TypeScript or Flow, which can only check the program flow at compile time, PHP will crash and burn if you pass an int into a string function parameter at runtime.<p>Would you expect the presumed type aliases to be checked at runtime too?<p>There are already union types in PHP 8, but no aliases.<p>I think in PHP it is always the best approach to work with classes, whose type you can check at runtime (in contrast to duck-typed languages such as JS, where there is instanceof but that is generally a last resort).<p>Structural types checked at compile time are a different approach to the one PHP chose I think. Alhough the lines between compilation and execution are blurry in a JIT language of course.
stefanos82超过 1 年前
That is something I was looking for to be honest with you, but didn&#x27;t know how to &quot;look&quot; for it lol.<p>I had in mind the modern C++ `using` mechanism for creating my own types, but didn&#x27;t know how to write such logic.<p>I guess a union would be handy dealing with different alias types, depending on the use case, if you understand what I mean.<p>On the other hand, `match` is far better to be used if we really get type aliases as you suggest.
stefanos82超过 1 年前
How about overloading `as` operator instead and use `alias` in place of `type`?<p>Something like `alias Numeric as int|float;`
评论 #38034065 未加载