Why php's string is a value type? It is copied all over the place every time the argument is passed to a function, every time the assignment is made, every concatenation causes string to be copied. My .NET experience tells me that it seems inefficient and forces me to use references almost everywhere. Consider the following alternatives:
Alternative 1
// This implementation hurts performance
class X {
public $str;
function __construct($str) { // string copied during argument pass
$this->$str = $str; // string copied here during assignment
}
}
Alternative 2
// This implementation hurts security
class Y {
public $str;
function __construct(&$str) {
$this->$str = &$str;
}
}
// because
$var = 'var';
$y = new Y($var);
$var[0] = 'Y';
echo $y->var; // shows 'Yar'
Alternative 3
// This implementation is a potential solution, the callee decides
// whether to pass the argument by reference or by value, but
// unfortunately it is considered 'deprecated'
class Z {
public $str;
function __construct($str) {
$this->$str = &$str;
}
}
// but
$var = 'var';
$z = new Z(&$var); // warning jumps out here
$var[0] = 'Z';
echo $y->var; // shows 'Zar'
The question: What pain should I choose Performance / Security / Deprecation
Passing vars by reference is going to hurt performance.
Your example #1 is the best performance and best way to go about it.
PHP handle's it's variables pretty reasonably. Internally, PHP uses a copy-on-modification system.
That is to say that those values will be assigned by reference until one of them is changed, in which case it will get a new slot in memory for the new value.