Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

swift

I have recently started with learning Swift for iOS development. I have a background in scripting languages, especially PHP. Seeing that it is emphasized using let to define a constant in favor of var to have the compiler optimize the resulting code, I wondered: is there an equivalent for PHP? Or does it simply not apply as PHP is not statically compiled?

I tried my luck at searching but found no satisfying information on that point.

like image 605
herrbischoff Avatar asked Sep 16 '25 09:09

herrbischoff


1 Answers

No, you can't have locally scoped constants in PHP. All PHP constants are always globally visible. There is also no concept like immutable/mutable variables.

You can implement immutable object members (PHP: immutable public member fields), but it's a different thing.

Actually there is a const keyword in the language, but the docs say:

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)

Interpreted languages with a dynamic type systems can have something like the swift let statement, so this is not because swift is compiled and PHP is interpreted (for example, there is a javascript proposal to introduce that feature: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/const)

like image 173
stefreak Avatar answered Sep 19 '25 03:09

stefreak