gpt4 book ai didi

php - 使用 'new' 实例化时到底发生了什么?

转载 作者:IT王子 更新时间:2023-10-29 00:13:24 25 4
gpt4 key购买 nike

让我们考虑以下代码:

class a {
public $var1;
function disp(){
echo $this->var1;
}
}

$obj1 = new a;
echo '<br/>After instantiation into $obj1:<br/>';
xdebug_debug_zval('obj1');

$obj1->var1 = "Hello ";
echo '<br/><br/>After assigning "Hello" to $obj->var1:<br/>';
$obj1->disp();

echo "<br/><br/>";
xdebug_debug_zval('obj1');

输出:

After instantiation into $obj1:
obj1: (refcount=1, is_ref=0)=class a { public $var1 = (refcount=2, is_ref=0)=NULL }

After assigning "Hello" to $obj->var1:
Hello

obj1: (refcount=1, is_ref=0)=class a { public $var1 = (refcount=1, is_ref=0)='Hello ' }

一个接一个:

After instantiation into $obj1:
obj1: (refcount=1, is_ref=0)=class a { public $var1 = (refcount=2, is_ref=0)=NULL }

当只有一个对象是 a 类时,为什么 $obj1->var1refcount=2

是因为 new 运算符如何赋值吗?PHP 使用引用进行赋值。当用 new 实例化时,没有符号/变量名称与该实例相关联。但是,类属性确实有名称。 recount=2是因为这个吗?

如果是这种情况,则发生了 C.O.W(写时复制),浅拷贝 WRT 类实例。虽然属性仍然指向在使用 new 实例化期间创建的 zval 属性。

现在,

After assigning "Hello" to $obj->var1:
Hello

obj1: (refcount=1, is_ref=0)=class a { public $var1 = (refcount=1, is_ref=0)='Hello ' }

因此,当我为属性 $obj1->var1 赋值时,该属性的新 zval 容器以及 refcount=1

这是否意味着在实例化期间使用 new 创建的 zval 容器仍然存在但无法访问,因为没有与之关联的符号/变量名称?

请注意(来自 xdebug: Variable Display Features ):
debug_zval_dump() 不同于 xdebug_debug_zval()

void xdebug_debug_zval( [string varname [, ...]] )

Displays information about a variable.

This function displays structured information about one or more variables that includes its type, value and refcount information. Arrays are explored recursively with values. This function is implemented differently from PHP's debug_zval_dump() function in order to work around the problems that that function has because the variable itself is actually passed to the function. Xdebug's version is better as it uses the variable name to lookup the variable in the internal symbol table and accesses all the properties directly without having to deal with actually passing a variable to a function. The result is that the information that this function returns is much more accurate than PHP's own function for showing zval information.

更新:2011 年 12 月 31 日:

I am trying to look at how memory allocation takes place when new is used. But There are too many other things I have to do right now. I hope I will be able to post an useful update soon. Until then here are the links to code at which I was looking at :

最佳答案

添加另一个实例 $obj2 = new a; 将引用计数增加到 3,而不是 4,因此这是调用 xdebug_debug_zval 的结果。 xdebug 函数的目的是避免因将变量传递给函数和(可能)创建额外引用而造成的混淆。

不幸的是,这不适用于成员变量;为这些 zval 创建了另一个引用以导出它们。因此,debug_zval_dump documentation 上注释中列出的所有注意事项和令人困惑的情况。仍然申请成员变量。

关于php - 使用 'new' 实例化时到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8668664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com