05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The object created bythe Person constructor is copied, and the copyis stored in<br />

$fred. This means that $this in the constructor and $fred actuallyrefer to two different<br />

objects. If the constructor creates an alias to $this through a reference, it won’t<br />

create an alias to $fred. For example:<br />

$people = array();<br />

class Person {<br />

function Person () {<br />

global $people;<br />

$people[] =& $this;<br />

}<br />

}<br />

$fred = new Person;<br />

$fred->name = "Fred";<br />

$barney =& new Person;<br />

$barney->name = "Barney";<br />

var_dump($people);<br />

array(2) {<br />

[0]=><br />

&object(person)(0) {<br />

}<br />

[1]=><br />

&object(person)(1) {<br />

["name"]=><br />

string(6) "Barney"<br />

}<br />

}<br />

$fred is a copyof the object that the constructor stored in $people[0], while $barney<br />

is an alias for the object that the constructor stored in $people[1]. When we change<br />

the properties of $fred, we’re not changing the object that is in $people[0]. However,<br />

when we change the properties of $barney, we are changing the object in<br />

$people[1].<br />

To prevent copying on assignment, assign by reference:<br />

$obj =& new Class;<br />

This code makes $obj an alias for the new object, which was $this in the constructor.<br />

If the constructor stores a reference to $this, it keeps a reference to $obj.<br />

The documentation for a class should saywhether you need to use =& with its constructor.<br />

In most cases, this isn’t necessary.<br />

Introspection<br />

Introspection is the abilityof a program to examine an object’s characteristics, such<br />

as its name, parent class (if any), properties, and methods. With introspection, you<br />

can write code that operates on anyclass or object. You don’t need to know which<br />

methods or properties are defined when you write your code; instead, you can discover<br />

that information at runtime, which makes it possible for you to write generic<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Introspection | 147

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!