Php字符串是值类型?

Lu4*_*Lu4 2 php security performance

为什么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
// 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'
Run Code Online (Sandbox Code Playgroud)

问题:我应该选择什么样的性能/安全/弃用

Cra*_*ige 10

PHP处理它的变量非常合理.在内部,PHP使用复制修改系统.

也就是说,这些值将通过引用分配,直到其中一个值发生更改,在这种情况下,它将在内存中为新值获取新的插槽.