php字符串是值类型?

标签 php performance security

为什么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/

相关文章:

php - 如何将mysql改为mysqli?

security - 将 session 存储在加密的 cookie 中

php - 逗号分隔区域设置的微秒损失

PHP 持续时间下拉列表

python - 按索引对数组子集的标准差进行多次计算

performance - 在具有多个子项的 PostgreSQL 中使用继承会降低性能吗?

iphone - 圆形 UIScrollView 性能

security - ckan:阻止用户自动注册

android - 亚马逊 AppStore 提交失败 : "Sensitive information like password is echoed in clear text without encryption"

php - 摆脱这个代理