Setting the record straight directly in the manual about object references

git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@262311 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
Etienne Kneuss 2008-07-09 00:19:48 +00:00
parent 31863a641f
commit e330479f66

View file

@ -0,0 +1,87 @@
<?xml version="1.0" encoding="iso-8859-1"?>
<!-- $Revision: 1.1 $ -->
<sect1 xml:id="language.oop5.references" xmlns="http://docbook.org/ns/docbook">
<title>Objects and references</title>
<para>
One of the key-point of PHP5 OOP that is often mentioned is that
"objects are passed by references by default" This is not completely true.
This section rectifies that general thought using some examples.
</para>
<para>
A PHP reference is an alias, which allows two different variables to write
to the same value. As of PHP5, an object variable doesn't contain the object
itself as value anymore. It only contains a object identifier which allows
object accessors to find the actual object. When an object is sent by
argument, returned or assigned to another variable, the different variables
are not aliases: they hold a copy of the identifier, which points to the same
object.
</para>
<example>
<title>References and Objects</title>
<programlisting role="php">
<![CDATA[
<?php
class A {
public $foo = 1;
}
$a = new A;
$b = $a; // $a and $b are copies of the same identifier
// ($a) = ($b) = <id>
$b->foo = 2;
echo $a->foo."\n";
$c = new A;
$d = &$c; // $c and $d are references
// ($c,$d) = <id>
$d->foo = 2;
echo $c->foo."\n";
$e = new A;
function foo($obj) {
// ($obj) = ($e) = <id>
$obj->foo = 2;
}
foo($e);
echo $e->foo."\n";
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
2
2
2
]]>
</screen>
</example>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->