为什么php的string是值类型?每次将参数传递给函数时,每次进行赋值时,每次连接都会导致字符串被复制,它会被复制到各处。我的 .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
}
}
备选方案 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'
备选方案 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'
问题:我应该选择性能/安全/弃用什么痛苦
最佳答案
PHP 非常合理地处理它的变量。在内部,PHP 使用修改时复制系统。
也就是说,这些值将通过引用分配,直到其中一个值发生更改,在这种情况下,它将在内存中为新值获取一个新槽。
关于php字符串是值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4565518/