volka wrote:stereofrog wrote:Objects in php5 are pointers (not references)
Are there any differences in php? What's a pointer in php?
During the execution php maintains the list of variables and their values (so-called symbol table). When you assign one variable to another
php allocates a new entry in the symbol table and copies the value from $a to $b. The symbol table looks then like this
$a and $b are not linked together in any way, if you assign something else to $b, $a won't be affected. This behaviour is common for php4 and 5, the key difference is that "object" values are stored immediately in php4, while php5 stores only the memory address of the object i.e. pointer.
in php4 symbol table will be
Code: Select all
a -> {source object}
b -> {copy of the object}
and in php5
Code: Select all
a -> 0x1234 \
|-> {source object}
b -> 0x1234 /
that is, "new X" returns the "whole object" in php4 and only a pointer in php5.
Pointer value is like any other, and there's no difference for the engine if you assign a pointer or an integer, however when you dereference the pointer and change the object itself
this also indirectly changes $b, just because $b happens to have the same pointer value as $a. But this doesn't mean $a and $b "know" of each other, they remain independent just like before.
Reference is somewhat completely different. References are aliases, assigning by reference
essentially means: "$c is another name for $a". Of course, $c and $a are then wired together, changing $c will also change $a.
This reasoning exactly applies to the function calls. When a function is being called, engine creates a new symbol table and copies arguments' values to the new variables. Arguments passed by value are independent from their "sources", but can affect them by dereferencing:
Code: Select all
function foo($copy) {
$copy->x = 123; // indirectly affects $source
$copy = 999; // doesn't affect $source
}
$source = new X;
foo($source);
When passing by reference, the function variable becomes an alias to the source and can change it directly:
Code: Select all
function bar(& $ref) {
$ref = 999; // changes $source
}
$source = new A;
bar($source);
// - source got a new value
References are harmful, because they change the calling scope in an often unobvious way, resulting in undesired side effects. In php4, passing by reference was basically a hack to let a function change a passed object, in php5 this is not needed, and it's better to forget about references completely. Most comparable languages doesn't support references, that doesn't make them less powerful.
Hope this was helpful.
