php字符串是值类型吗? [英] Php string is a value type?

查看:46
本文介绍了php字符串是值类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么php的字符串是值类型?每次将参数传递给函数时,每次进行赋值时,每次连接都会导致字符串被复制.我的 .NET 经验告诉我它似乎效率低下并迫使我几乎在任何地方都使用引用.考虑以下替代方案:

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:

备选方案 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'

问题:我应该选择性能/安全/弃用有什么痛苦

The question: What pain should I choose Performance / Security / Deprecation

推荐答案

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

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.

这篇关于php字符串是值类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆