Hey Larry,

> On 1 Feb 2015, at 00:42, Larry Garfield <la...@garfieldtech.com> wrote:
> 
> Immutability, generally, offers two advantages:
> 
> 1) It makes it easier for humans to reason about code.
> 
> 2) It makes it easier for compilers/runtimes to reason about code.
> 
> For the former, good programming practices/standards can often suffice as 
> there are cases where immutability makes code uglier, not better.
> 
> For the latter, it allows the compiler/runtime to do two things: Catch code 
> errors early and optimize based on assumptions.

PHP doesn’t have immutable classes, though, so the PHP runtime *can’t* reason 
about code using value objects and such, and they’re less performant than 
mutable objects with manual copying.

I think having some means to create value type classes (i.e. PHP 4-style 
classes) would be beneficial. These classes would have the same always-copy or 
copy-on-write behaviour that PHP’s scalar types and arrays have. They’d be 
performant compared to immutable classes like PSR-7’s, because operations 
mutate the value in-place if possible, rather than creating a new class. They’d 
also be nicer to use, because you can change the value imperatively rather than 
having to chain together return values. But you keep the main advantages of 
immutable types: no spooky action at a distance, no explicit copying needed.

> What *could* be valuable, however, is flagging *parameters*.  Ie:
> 
> function foo(const MyClass $c, const $s) {
>  $s = 'abc'; // Compiler error
>  $c = new MyClass(); // Compiler error.
>  $c->foo = 'abc'; // Some kind of error?
> }
> 

const parameters are a cool feature in C. However, the main use for them in C 
doesn’t really exist in PHP. In C, most of the time you need to pass a pointer 
to a value to a function, rather than a value directly. Having a pointer to a 
value means you can modify that value. So, there’s a need for a “const” 
modifier to mark parameters as being for values that will be taken as input and 
not modified, rather than as values that will be used as output and modified.

PHP, on the other hand, doesn’t have pointers. Parameters are usually by-value 
(objects are by-reference, but still). If you want to mutate some value, you 
need to explicitly mark it as such… most parameters are already “constant”.

Though, I suppose there’s some usefulness in that, since all objects are 
by-reference, you might want to say you won’t touch that object. Hmm. Given 
that PHP is dynamic, not compiled, and function calls can have side effects, 
though, this would be difficult to enforce. You’d need to check that all calls 
made within the function do not have any side effects on that value…

I’m not sure how workable this is.

Thanks.
--
Andrea Faulds
http://ajf.me/





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

Reply via email to