Wednesday, March 21, 2007

assignment operator in PHP4 and PHP5

The assignment(=) copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop. Since PHP 4, assignment by reference has been supported, using the $var = &$othervar; syntax, but this is not possible in PHP 3. 'Assignment by reference' means that both variables end up pointing at the same data, and nothing is copied anywhere. To learn more about references, please read References explained.
As of PHP5 objects are assigned by reference
unless explicitly told otherwise with the new clone keyword.


如果是php4,在new一个class对象是copy操作,copy 了等号右边的原始对象赋给左边的变量,所以左边那个变量操作是与原来右边的对象是独立的,即通过对象操作改变了左边对象里的某个属性值,原来等号右边的对象仍然是原始初始化所赋的值。具体例子见php5手册里关于php4 reference的例子。如果需要操作此对象影响到右边的new出来的对象,则需要用到reference assignment(=&)。
在php5中默认就是reference assignment,除非明确声明是clone此对象。

No comments :