tags:

views:

67

answers:

2

In PHP, reference variables modify both when 1 or the other is changed.

New classes are formed by implicit references, but modifying the extension does not modify the parent.

Is this by PHP's design, or are they different kinds of "references?"

+1  A: 

You are confusing subclassing (extending) with references.

This is extending, which is what you described:

class ParentClass{ };
class ChildClass extends ParentClass { };

$parent = new ParentClass;
$child = new ChildClass;

$parent->setName('Dad');
$child->setName('Daughter');

echo $parent->name;
// Dad

Is that, in fact, what you wanted to be describing?

Passing variables/classes by reference is a completely different conversation and isn't really connected to the idea of subclassing/extending a class. It works more like this.

$parent = new ParentClass;
$child = new ChildClass;

$childRef = $child; // $childRef isn't a copy, it's a reference to $child.
$childRef->setName('Daughter');

echo $child->name;
// Daughter
// Notice that it's the same as if you had called setName( ) on $child itself;
conceptDawg
A: 

References in PHP are a weird construct. $a =& $b; makes $a a reference to $b. This means that whenever the value of $b changes, $a will reflect that change. Or put differently, $a will always have the same value as $b.

In PHP 4, objects would be implicitly cloned when assigning them. Eg. if $b is an object, the code $a = $b would create a new object, which is a copy of $b, and assign it to $a. This is rather a problem, since you usually want reference semantics on objects. To get around this, you had to use references when dealing with objects. Since PHP 5 this has changed, so today there are very few cases (if any) where you should use references.

troelskn