为什么php的字符串是值类型?每次将参数传递给函数时,它都会被复制到每个位置,每次进行赋值时,每个连接都会导致复制字符串.我的.NET经验告诉我,它似乎效率低下,迫使我几乎无处不在地使用引用.考虑以下备选方案:
备选方案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
}
}
Run Code Online (Sandbox Code Playgroud)
备选方案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'
Run Code Online (Sandbox Code Playgroud)
备选方案3
// This implementation is a potential solution, the callee decides
// …Run Code Online (Sandbox Code Playgroud)