php – 用“新”实例化时究竟发生了什么?

让我们考虑以下代码:

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 }

为什么$ obj1> var1有refcount = 2,当只有一个对象的类a?

是因为新操作符如何进行分配?
PHP使用引用进行分配。当用新的实例化时,没有符号/变量名与该实例相关联。但是,类属性确实有名称。由于这个原因,recount = 2?

如果是这种情况,那么就会发生一个C.O.W(copy on write),一个浅拷贝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?

这是否意味着在实例化过程中创建的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 07001 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 :

  • 07002
  • 07003
  • 07004
  • 07005
添加另一个实例化$ obj2 = new a;将引用计数增加到3,而不是4,所以这是因为调用xdebug_debug_zval而发生的。 xdebug函数的目的是避免将变量传递到函数中的困惑(可能)创建额外的引用。

不幸的是,这不适用于成员变量;为了导出它们,为这些ZARE创建了另一个引用。因此,debug_zval_dump documentation年度注释中列出的所有注意事项和混淆情况仍然适用于成员变量。

http://stackoverflow.com/questions/8668664/what-is-exactly-happening-when-instantiating-with-new

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:php – 用“新”实例化时究竟发生了什么?