Hi!

> What I want to discuss is true immutability flag for variables and
> parameters. There are a lot of languages that use "final" or "const"
> keywords to prevent modification of variables. We can use this approach by
> extending language syntax as following:

Most of the languages that use "final" and "const" do much more than
"prevent modification of variables" - they make these "variables"
constants, which behave differently. Also, many of them fail to achieve
the actual immutability - "const" declaration just means you can't
assign/mutate this name, but says nothing about the object the name
points to - it can very well still be mutated by other means. E.g. if
you declare "const $foo = new MyObject();" you have no control over what
any method called on $foo does. You'd need to introduce const methods
and have checks to ensure they are actually not changing the object
(which may have serious performance impacts).

For all this, I'd like to ask - why? Immutable object are very useful in
concurrency applications, since they allow to avoid expensive
synchronization costs and make it much easier to reason about system's
state (which is arguably impossible to predict with mutable objects in a
parallel system). But PHP has no parallelism. So which benefit would
that provide? If you want an immutable object, just make all properties
protected and provide getters but not setters. This is easily doable
without any keywords. Having immutable scalar variable seems a bit
useless since the scope of the scalar variable is very small and if you
can't track what happens inside a single function you probably should
refactor this function, not the language.

There might be optimizations available for immutable scalars, but we
already have constants for that.

> 
> const $text = "Some message"; // defines an immutable variable that can not
> be modified.
> $text .= "foo"; // Exception: can not change the immutable variable
> 
> class Test {
>     public final $value; // final keyword defines immutable property, but
> it isn't initialized yet so allows only one assignment, then will be
> immutable

So each property would have a counter which tracks if it's assigned or
not? That would be rather weird - what if the ctor doesn't initialize
it? Then random method that tries to assign it would work once but not
twice, which would be very weird.

> On the engine level this immutable variables and parameters can be
> effectively optimized by using IS_TYPE_IMMUTABLE for zval. This can result
> in achieving better performance and various JIT-optimizations.

I don't see how they can be optimized unless they are actually constants
(yours are not, since they can be assigned with arbitrary value in
runtime, albeit just once) - and we already have constants.

-- 
Stas Malyshev
smalys...@gmail.com

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to