在 PHP 中是否存在 "let" 与 "var" 的等价物?

Is there an equivalent of "let" vs. "var" in PHP?

我最近开始学习 Swift 以进行 iOS 开发。我有脚本语言方面的背景,尤其是 PHP。看到强调使用 let 来定义一个有利于 var 的常量来让编译器优化结果代码,我想知道:是否有 PHP 的等价物?或者它根本不适用,因为 PHP 不是静态编译的?

我尝试了搜索,但没有找到关于这一点的令人满意的信息。

不,在 PHP 中不能有局部范围的常量。所有 PHP 常量始终全局可见。也没有像 immutable/mutable 变量这样的概念。

您可以实现不可变对象成员 (PHP: immutable public member fields),但这是另一回事。

实际上语言中有一个 const 关键字,但文档说:

Note:

As opposed to defining constants using define(), constants defined using the const keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops, if statements or try/ catch blocks.

(from http://php.net/manual/en/language.constants.syntax.php)

具有动态类型系统的解释型语言 可以 有类似 swift let 语句的东西,所以这不是因为 swift 是compiled and PHP is interpreted(例如,有一个 javascript proposal to introduce that feature: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/const

Is there an equivalent of “let” vs. “var” in PHP?

PHP 没有 let 作为母语功能,但(截至当前版本 7.1.4 - 04/2017)

但是,一些高性能扩展如 Phalcon and Ice have support for let, because of the underlying usage of zephir-lang。 所以,有let,但是是间接的;使用上述扩展。

有两个用例:


例如,查看 Ice Router:

的来源
namespace Ice\Mvc\Route;

use Ice\Mvc\Route\Parser\ParserInterface;
use Ice\Mvc\Route\DataGenerator\DataGeneratorInterface;
use Ice\Mvc\Route\Parser\Std;
use Ice\Mvc\Route\DataGenerator\GroupCount as Generator;

class Collector
{

    private routeParser { set };
    private dataGenerator { set };

    /**
     * Constructs a route collector.
     *
     * @param RouteParser   $routeParser
     * @param DataGenerator $dataGenerator
     */
    public function __construct(<ParserInterface> routeParser = null, <DataGeneratorInterface> dataGenerator = null)
    {
        if !routeParser {
            let routeParser = new Std();
        }

        if !dataGenerator {
            let dataGenerator = new Generator();
        }

        let this->routeParser = routeParser,
            this->dataGenerator = dataGenerator;
    }

    /**
     * Adds a route to the collection.
     *
     * The syntax used in the $route string depends on the used route parser.
     *
     * @param string|array $httpMethod
     * @param string $route
     * @param mixed  $handler
     */
    public function addRoute(var httpMethod, string route, handler = null)
    {
        var routeDatas, routeData, method;

        let routeDatas = this->routeParser->parse(route);

        if typeof httpMethod == "string" {
            let method = httpMethod,
                httpMethod = [method];
        }

        for method in httpMethod {
            for routeData in routeDatas {
                this->dataGenerator->addRoute(method, routeData, handler);
            }
        }
    }

    /**
     * Returns the collected route data, as provided by the data generator.
     *
     * @return array
     */
    public function getData()
    {
        return this->dataGenerator->getData();
    }
}