Re: [RFC] Immutable variables and objects

From: Date: Mon, 02 Feb 2015 10:01:56 +0000
Subject: Re: [RFC] Immutable variables and objects
References: 1 2 3 4 5 6  Groups: php.internals 
Request: Send a blank email to internals+get-81578@lists.php.net to get a copy of this message
Lester Caine wrote on 02/02/2015 09:19:
This is probably because I still don't understand objects, as I still just consider them as arrays with a few more complex elements. I STILL work on the basis that is I pass by reference, I can make modifications to the data while if I don't I get a copy and have to pass the copy back if I need the original changed. This used to be all very simple, so when did it stop working? This may explain why I get into trouble with stuff that has been working for years but after 'modernising' starts throwing problems :(
Since PHP 5, and in most other languages, objects are passed with an extra level of indirection, almost but not quite the same as pass-by-reference. So there are actually three ways a variable can be passed (or assigned): - scalar by value - an assignment to the variable changes only that variable - scalar by reference, using & - both variable names point to the same variable, and assigning a value to one assigns it to both - object by value - an assignment to the variable still only changes that variable, BUT two variables can point at the same object can both modify its internal state. So if you have $current_user = getCurrentUserObject(); then saying $current_user = null; is changing its value, so would only change that variable, but $current_user->setPassword('1234'); is not, so the change would be visible from all variables pointing at that object. Immutable parameters for scalars and arrays are simple: currently you can use a by-value parameter as a local variable in your function, but you might want to avoid the confusion of this: function foo( const $bar ) { $bar = 42; // ERROR } or foo( const array $bar ) { $bar[] = 42; // ERROR } Immutable parameters for objects are complicated, because foo( const $bar ) { $bar->value = 42; } is not technically changing the *value* of that object, but it would be useful to have an enforcement that it wouldn't happen. Hope that clarifies things a bit. Regards, -- Rowan Collins [IMSoP] ||

« previous php.internals (#81578) next »