1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 297028 $ -->
<appendix xml:id="oop4" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>Classes and Objects (PHP 4)</title>
<sect1 xml:id="keyword.class">
<title><literal>class</literal></title>
<para>
A class is a collection of variables and functions working with
these variables. Variables are defined by <literal>var</literal> and
functions by <literal>function</literal>. A class is defined using the
following syntax:
</para>
<para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class Cart {
var $items; // Items in our shopping cart
// Add $num articles of $artnr to the cart
function add_item($artnr, $num) {
$this->items[$artnr] += $num;
}
// Take $num articles of $artnr out of the cart
function remove_item($artnr, $num) {
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} elseif ($this->items[$artnr] == $num) {
unset($this->items[$artnr]);
return true;
} else {
return false;
}
}
}
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
This defines a class named Cart that consists of an associative
array of articles in the cart and two functions to add and remove
items from this cart.
</para>
<warning>
<simpara>
You can <emphasis>NOT</emphasis> break up a class definition into
multiple files. You also can <emphasis>NOT</emphasis> break a class
definition into multiple PHP blocks, unless the break is within a method
declaration. The following will not work:
</simpara>
<para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class test {
?>
<?php
function test() {
print 'OK';
}
}
?>
]]>
</programlisting>
</informalexample>
</para>
<simpara>
However, the following is allowed:
</simpara>
<para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class test {
function test() {
?>
<?php
print 'OK';
}
}
?>
]]>
</programlisting>
</informalexample>
</para>
</warning>
<simpara>
The following cautionary notes are valid for PHP 4.
</simpara>
<caution>
<simpara>
The name <literal>stdClass</literal> is used internally by
Zend and is reserved. You cannot have a class named
<literal>stdClass</literal> in PHP.
</simpara>
</caution>
<caution>
<simpara>
The function names <literal>__sleep</literal> and
<literal>__wakeup</literal> are magical in PHP classes. You
cannot have functions with these names in any of your
classes unless you want the magic functionality associated
with them. See below for more information.
</simpara>
</caution>
<caution>
<simpara>
PHP reserves all function names starting with <literal>__</literal> as magical.
It is recommended that you do not use function names with
<literal>__</literal> in PHP unless you want some documented magic functionality.
</simpara>
</caution>
<simpara>
In PHP 4, only constant initializers for <literal>var</literal>
variables are allowed. To initialize variables with non-constant
values, you need an initialization function which is called
automatically when an object is being constructed from the
class. Such a function is called a constructor (see below).
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class Cart {
/* None of these will work in PHP 4. */
var $todays_date = date("Y-m-d");
var $name = $firstname;
var $owner = 'Fred ' . 'Jones';
/* Arrays containing constant values will, though. */
var $items = array("VCR", "TV");
}
/* This is how it should be done. */
class Cart {
var $todays_date;
var $name;
var $owner;
var $items = array("VCR", "TV");
function Cart() {
$this->todays_date = date("Y-m-d");
$this->name = $GLOBALS['firstname'];
/* etc. . . */
}
}
?>
]]>
</programlisting>
</informalexample>
<para>
Classes are types, that is, they are blueprints for actual
variables. You have to create a variable of the desired type with
the <literal>new</literal> operator.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$cart = new Cart;
$cart->add_item("10", 1);
$another_cart = new Cart;
$another_cart->add_item("0815", 3);
?>
]]>
</programlisting>
</informalexample>
<para>
This creates the objects <varname>$cart</varname> and
<varname>$another_cart</varname>, both of the class Cart. The function
<literal>add_idem()</literal> of the <varname>$cart</varname> object is being called to add 1
item of article number 10 to the <varname>$cart</varname>. 3 items of
article number 0815 are being added to <varname>$another_cart</varname>.
</para>
<para>
Both, <varname>$cart</varname> and <varname>$another_cart</varname>, have
functions <literal>add_item()</literal>, <literal>remove_item()</literal>
and a variable <varname>items</varname>. These are distinct functions and variables. You can
think of the objects as something similar to directories in a filesystem.
In a filesystem you can have two different files
<filename>README.TXT</filename>, as long as they are in different directories.
Just like with directories where you'll have to type the full pathname in
order to reach each file from the toplevel directory, you have to specify
the complete name of the function you want to call: in PHP terms, the
toplevel directory would be the global namespace, and the pathname separator
would be <literal>-></literal>. Thus, the
names <varname>$cart->items</varname> and
<varname>$another_cart->items</varname> name two different variables.
Note that the variable is named <varname>$cart->items</varname>, not
<varname>$cart->$items</varname>, that is, a variable name in PHP has
only a single dollar sign (<literal>$</literal>).
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// correct, single $
$cart->items = array("10" => 1);
// invalid, because $cart->$items becomes $cart->""
$cart->$items = array("10" => 1);
// correct, but may or may not be what was intended:
// $cart->$myvar becomes $cart->items
$myvar = 'items';
$cart->$myvar = array("10" => 1);
?>
]]>
</programlisting>
</informalexample>
<para>
Within a class definition, you do not know under which name the object
will be accessible in your program: at the time the Cart class was
written, it was unknown whether the object would be named
<varname>$cart</varname>, <varname>$another_cart</varname>, or something
else later. Thus,
you cannot write <varname>$cart->items</varname> within the Cart class
itself. Instead, in order to be able to access its own functions and
variables from within a class, one can use the pseudo-variable
<varname>$this</varname> which can be read as 'my own' or 'current
object'. Thus, '<varname>$this->items[$artnr]</varname> +=
<varname>$num</varname>' can be read as 'add <varname>$num</varname> to
the <varname>$artnr</varname> counter of my own items array' or 'add
<varname>$num</varname> to the <varname>$artnr</varname> counter of the
items array within the current object'.
</para>
<note>
<para>
The <varname>$this</varname> pseudo-variable is not usually defined if
the method in which it is hosted is called statically. This is not,
however, a strict rule: <varname>$this</varname> is defined if a method is
called statically from within another object. In this case, the value of
<varname>$this</varname> is that of the calling object. This is
illustrated in the following example:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}
class B
{
function bar()
{
A::foo();
}
}
$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.
]]>
</screen>
</informalexample>
</para>
</note>
<note>
<para>
There are some nice functions to handle classes and objects. You might want
to take a look at the <link linkend="ref.classobj">Class/Object
Functions</link>.
</para>
</note>
</sect1>
<sect1 xml:id="keyword.extends">
<title><literal>extends</literal></title>
<para>
Often you need classes with similar variables and functions
to another existing class. In fact, it is good practice to
define a generic class which can be used in all your
projects and adapt this class for the needs of each of your
specific projects. To facilitate this, classes can be
extensions of other classes. The extended or derived class
has all variables and functions of the base class (this is
called 'inheritance' despite the fact that nobody died) and what
you add in the extended definition. It is not possible to
subtract from a class, that is, to undefine any existing
functions or variables. An extended class is always dependent
on a single base class, that is, multiple inheritance is
not supported. Classes are extended using the keyword '<literal>extends</literal>'.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class Named_Cart extends Cart {
var $owner;
function set_owner ($name) {
$this->owner = $name;
}
}
?>
]]>
</programlisting>
</informalexample>
<para>
This defines a class Named_Cart that has all variables and functions of
Cart plus an additional variable <varname>$owner</varname> and an
additional function <literal>set_owner()</literal>. You create a named cart the usual way and
can now set and get the carts owner. You can still use normal cart
functions on named carts:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$ncart = new Named_Cart; // Create a named cart
$ncart->set_owner("kris"); // Name that cart
print $ncart->owner; // print the cart owners name
$ncart->add_item("10", 1); // (inherited functionality from cart)
?>
]]>
</programlisting>
</informalexample>
<para>
This is also called a "parent-child" relationship. You create a class,
parent, and use <literal>extends</literal> to create a new class
<emphasis>based</emphasis> on the parent class: the child class. You can
even use this new child class and create another class based on this child
class.
</para>
<note>
<para>
Classes must be defined before they are used! If you want the class
<literal>Named_Cart</literal> to extend the class
<literal>Cart</literal>, you will have to define the class
<literal>Cart</literal> first. If you want to create another class called
<literal>Yellow_named_cart</literal> based on the class
<literal>Named_Cart</literal> you have to define
<literal>Named_Cart</literal> first. To make it short: the order in which
the classes are defined is important.
</para>
</note>
</sect1>
<sect1 xml:id="oop4.constructor">
<title>Constructors</title>
<para>
Constructors are functions in a class that are automatically
called when you create a new instance of a class with
<literal>new</literal>. A function becomes a constructor, when
it has the same name as the class. If a class
has no constructor, the constructor of the base class will be
called, if it exists.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class Auto_Cart extends Cart {
function Auto_Cart() {
$this->add_item("10", 1);
}
}
?>
]]>
</programlisting>
</informalexample>
<para>
This defines a class Auto_Cart that is a Cart plus a constructor
which initializes the cart with one item of article number "10"
each time a new Auto_Cart is being made with "<literal>new</literal>".
Constructors can take arguments and these arguments can be optional, which
makes them much more useful. To be able to still use the class
without parameters, all parameters to constructors should be
made optional by providing default values.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class Constructor_Cart extends Cart {
function Constructor_Cart($item = "10", $num = 1) {
$this->add_item ($item, $num);
}
}
// Shop the same old boring stuff.
$default_cart = new Constructor_Cart;
// Shop for real...
$different_cart = new Constructor_Cart("20", 17);
?>
]]>
</programlisting>
</informalexample>
<para>
You also can use the <literal>@</literal> operator to
<emphasis>mute</emphasis> errors occurring in the constructor, e.g.
<literal>@new</literal>.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class A
{
function A()
{
echo "I am the constructor of A.<br />\n";
}
function B()
{
echo "I am a regular function named B in class A.<br />\n";
echo "I am not a constructor in A.<br />\n";
}
}
class B extends A
{
}
// This will call B() as a constructor
$b = new B;
?>
]]>
</programlisting>
</informalexample>
<para>
The function B() in class A will suddenly become a
constructor in class B, although it was never intended to be.
PHP 4 does not care if the function is
being defined in class B, or if it has been inherited.
</para>
<caution>
<simpara>
PHP doesn't call constructors of the base class
automatically from a constructor of a derived class. It is
your responsibility to propagate the call to constructors
upstream where appropriate.
</simpara>
</caution>
<para>
Destructors are functions that are called automatically
when an object is destroyed, either with <function>unset</function>
or by simply going out of scope. There are no destructors
in PHP. You may use <function>register_shutdown_function</function>
instead to simulate most effects of destructors.
</para>
</sect1>
<sect1 xml:id="keyword.paamayim-nekudotayim"><!-- :-) -->
<title>Scope Resolution Operator (<literal>::</literal>)</title>
<caution>
<simpara>
The following is valid for PHP 4 and later only.
</simpara>
</caution>
<para>
Sometimes it is useful to refer to functions and variables
in base classes or to refer to functions in classes that
have not yet any instances. The <literal>::</literal> operator
is being used for this.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class A {
function example() {
echo "I am the original function A::example().<br />\n";
}
}
class B extends A {
function example() {
echo "I am the redefined function B::example().<br />\n";
A::example();
}
}
// there is no object of class A.
// this will print
// I am the original function A::example().<br />
A::example();
// create an object of class B.
$b = new B;
// this will print
// I am the redefined function B::example().<br />
// I am the original function A::example().<br />
$b->example();
?>
]]>
</programlisting>
</informalexample>
<para>
The above example calls the function <literal>example()</literal> in
class A, but there is no object of class A, so that
we cannot write <literal>$a->example()</literal> or similar. Instead we
call <literal>example()</literal> as a 'class function', that is, as a
function of the class itself, not any object of that
class.
</para>
<para>
There are class functions, but there are no class variables.
In fact, there is no object at all at the time of the call.
Thus, a class function may not use any object variables (but
it can use local and global variables), and it may not use
<varname>$this</varname> at all.
</para>
<para>
In the above example, class B redefines the function
<literal>example()</literal>. The original definition in class A is shadowed
and no longer available, unless you are referring specifically
to the implementation of <literal>example()</literal> in class A using the
::-operator. Write <literal>A::example()</literal> to do this (in fact, you
should be writing <literal>parent::example()</literal>, as shown in the next
section).
</para>
<para>
In this context, there is a current object and it may have object
variables. Thus, when used from WITHIN an object function, you may use
<varname>$this</varname> and object variables.
</para>
</sect1>
<sect1 xml:id="keyword.parent">
<title><literal>parent</literal></title>
<para>
You may find yourself writing code that refers to
variables and functions in base classes. This is
particularly true if your derived class is a refinement
or specialisation of code in your base class.
</para>
<para>
Instead of using the literal name of the base class in your
code, you should be using the special name
<literal>parent</literal>, which refers to the name of your
base class as given in the <literal>extends</literal>
declaration of your class. By doing this, you avoid using the
name of your base class in more than one place. Should
your inheritance tree change during implementation, the
change is easily made by simply changing the
<literal>extends</literal> declaration of your class.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class A {
function example() {
echo "I am A::example() and provide basic functionality.<br />\n";
}
}
class B extends A {
function example() {
echo "I am B::example() and provide additional functionality.<br />\n";
parent::example();
}
}
$b = new B;
// This will call B::example(), which will in turn call A::example().
$b->example();
?>
]]>
</programlisting>
</informalexample>
</sect1>
<sect1 xml:id="oop4.serialization">
<title>Serializing objects - objects in sessions</title>
<para>
<function>serialize</function> returns a string containing a
byte-stream representation of any value that can be stored in
PHP. <function>unserialize</function> can use this string to
recreate the original variable values. Using serialize to
save an object will save all variables in an object. The
functions in an object will not be saved, only the name of
the class.
</para>
<para>
In order to be able to <function>unserialize</function> an object, the
class of that object needs to be defined. That is, if you have an object
<varname>$a</varname> of class A on <filename>page1.php</filename> and serialize this, you'll
get a string that refers to class A and contains all values of variabled
contained in <varname>$a</varname>. If you want to be able to unserialize
this on <filename>page2.php</filename>, recreating <varname>$a</varname> of class A, the
definition of class A must be present in <filename>page2.php</filename>.
This can be done for example by storing the class definition of class A
in an include file and including this file in both
<filename>page1.php</filename> and <filename>page2.php</filename>.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// classa.inc:
class A {
var $one = 1;
function show_one() {
echo $this->one;
}
}
// page1.php:
include("classa.inc");
$a = new A;
$s = serialize($a);
// store $s somewhere where page2.php can find it.
$fp = fopen("store", "w");
fwrite($fp, $s);
fclose($fp);
// page2.php:
// this is needed for the unserialize to work properly.
include("classa.inc");
$s = implode("", @file("store"));
$a = unserialize($s);
// now use the function show_one() of the $a object.
$a->show_one();
?>
]]>
</programlisting>
</informalexample>
<para>
If you are using sessions and use <function>session_register</function>
to register objects, these objects are serialized automatically
at the end of each PHP page, and are unserialized automatically on
each of the following pages. This basically means that these objects
can show up on any of your pages once they become part of your
session.
</para>
<para>
It is strongly recommended that you include the class
definitions of all such registered objects on all of your
pages, even if you do not actually use these classes on all
of your pages. If you don't and an object is being
unserialized without its class definition being present, it
will lose its class association and become an object of class
<classname>__PHP_Incomplete_Class_Name</classname> without any functions available
at all, that is, it will become quite useless.
</para>
<para>
So if in the example above <varname>$a</varname> became part of a session
by running <literal>session_register("a")</literal>, you should include the
file <literal>classa.inc</literal> on all of your pages, not only <filename>page1.php</filename>
and <filename>page2.php</filename>.
</para>
</sect1>
<sect1 xml:id="oop4.magic-functions">
<title>The magic functions <literal>__sleep</literal> and <literal>__wakeup</literal></title>
<para>
<function>serialize</function> checks if your class has a function with
the magic name <literal>__sleep</literal>. If so, that function is
being run prior to any serialization. It can clean up the object
and is supposed to return an array with the names of all variables
of that object that should be serialized.
If the method doesn't return anything then &null; is serialized and
E_NOTICE is issued.
</para>
<para>
The intended use of <literal>__sleep</literal> is to commit pending
data or perform similar cleanup tasks. Also, the function is
useful if you have very large objects which need not be
saved completely.
</para>
<para>
Conversely, <function>unserialize</function> checks for the
presence of a function with the magic name
<literal>__wakeup</literal>. If present, this function can
reconstruct any resources that object may have.
</para>
<para>
The intended use of <literal>__wakeup</literal> is to
reestablish any database connections that may have been lost
during serialization and perform other reinitialization
tasks.
</para>
</sect1>
<sect1 xml:id="oop4.newref">
<title>References inside the constructor</title>
<para>
Creating references within the constructor can lead to confusing
results. This tutorial-like section helps you to avoid problems.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class Foo {
function Foo($name) {
// create a reference inside the global array $globalref
global $globalref;
$globalref[] = &$this;
// set name to passed value
$this->setName($name);
// and put it out
$this->echoName();
}
function echoName() {
echo "<br />", $this->name;
}
function setName($name) {
$this->name = $name;
}
}
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
Let us check out if there is a difference between
<varname>$bar1</varname> which has been created using
the copy <literal>=</literal> operator and
<varname>$bar2</varname> which has been created using
the reference <literal>=&</literal> operator...
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$bar1 = new Foo('set in constructor');
$bar1->echoName();
$globalref[0]->echoName();
/* output:
set in constructor
set in constructor
set in constructor */
$bar2 =& new Foo('set in constructor');
$bar2->echoName();
$globalref[1]->echoName();
/* output:
set in constructor
set in constructor
set in constructor */
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
Apparently there is no difference, but in fact there is a
very significant one: <varname>$bar1</varname> and
<varname>$globalref[0]</varname> are _NOT_ referenced, they
are NOT the same variable. This is because "<literal>new</literal>" does not
return a reference by default, instead it returns a copy.
<note>
<simpara>
There is no performance loss (since PHP 4 and up use reference
counting) returning copies instead of references. On the
contrary it is most often better to simply work with copies
instead of references, because creating references takes some
time where creating copies virtually takes no time (unless none
of them is a large array or object and one of them gets changed
and the other(s) one(s) subsequently, then it would be wise to
use references to change them all concurrently).
</simpara>
</note>
To prove what is written above let us watch the code below.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
// now we will change the name. what do you expect?
// you could expect that both $bar1 and $globalref[0] change their names...
$bar1->setName('set from outside');
// as mentioned before this is not the case.
$bar1->echoName();
$globalref[0]->echoName();
/* output:
set from outside
set in constructor */
// let us see what is different with $bar2 and $globalref[1]
$bar2->setName('set from outside');
// luckily they are not only equal, they are the same variable
// thus $bar2->name and $globalref[1]->name are the same too
$bar2->echoName();
$globalref[1]->echoName();
/* output:
set from outside
set from outside */
?>
]]>
</programlisting>
</informalexample>
</para>
<para>
Another final example, try to understand it.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class A {
function A($i) {
$this->value = $i;
// try to figure out why we do not need a reference here
$this->b = new B($this);
}
function createRef() {
$this->c = new B($this);
}
function echoValue() {
echo "<br />","class ",get_class($this),': ',$this->value;
}
}
class B {
function B(&$a) {
$this->a = &$a;
}
function echoValue() {
echo "<br />","class ",get_class($this),': ',$this->a->value;
}
}
// try to understand why using a simple copy here would yield
// in an undesired result in the *-marked line
$a =& new A(10);
$a->createRef();
$a->echoValue();
$a->b->echoValue();
$a->c->echoValue();
$a->value = 11;
$a->echoValue();
$a->b->echoValue(); // *
$a->c->echoValue();
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
class A: 10
class B: 10
class B: 10
class A: 11
class B: 11
class B: 11
]]>
</screen>
</informalexample>
</para>
</sect1>
<sect1 xml:id="oop4.object-comparison">
<title>Comparing objects</title>
<para>
In PHP 4, objects are compared in a very simple manner, namely: Two object
instances are equal if they have the same attributes and values, and are
instances of the same class. Similar rules are applied when comparing two
objects using the identity operator (<literal>===</literal>).
</para>
<para>
If we were to execute the code in the example below:
<example>
<title>Example of object comparison in PHP 4</title>
<programlisting role='php'>
<![CDATA[
<?php
function bool2str($bool) {
if ($bool === false) {
return 'FALSE';
} else {
return 'TRUE';
}
}
function compareObjects(&$o1, &$o2) {
echo 'o1 == o2 : '.bool2str($o1 == $o2)."\n";
echo 'o1 != o2 : '.bool2str($o1 != $o2)."\n";
echo 'o1 === o2 : '.bool2str($o1 === $o2)."\n";
echo 'o1 !== o2 : '.bool2str($o1 !== $o2)."\n";
}
class Flag {
var $flag;
function Flag($flag=true) {
$this->flag = $flag;
}
}
class SwitchableFlag extends Flag {
function turnOn() {
$this->flag = true;
}
function turnOff() {
$this->flag = false;
}
}
$o = new Flag();
$p = new Flag(false);
$q = new Flag();
$r = new SwitchableFlag();
echo "Compare instances created with the same parameters\n";
compareObjects($o, $q);
echo "\nCompare instances created with different parameters\n";
compareObjects($o, $p);
echo "\nCompare an instance of a parent class with one from a subclass\n";
compareObjects($o, $r);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Compare instances created with the same parameters
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE
Compare instances created with different parameters
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE
Compare an instance of a parent class with one from a subclass
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE
]]>
</screen>
</example>
Which is the output we will expect to obtain given the comparison rules
above. Only instances with the same values for their attributes
and from the same class are considered equal and identical.
</para>
<para>
Even in the cases where we have object composition, the same comparison
rules apply. In the example below we create a container class that stores
an associative array of <classname>Flag</classname> objects.
<example>
<title>Compound object comparisons in PHP 4</title>
<programlisting role='php'>
<![CDATA[
<?php
class FlagSet {
var $set;
function FlagSet($flagArr = array()) {
$this->set = $flagArr;
}
function addFlag($name, $flag) {
$this->set[$name] = $flag;
}
function removeFlag($name) {
if (array_key_exists($name, $this->set)) {
unset($this->set[$name]);
}
}
}
$u = new FlagSet();
$u->addFlag('flag1', $o);
$u->addFlag('flag2', $p);
$v = new FlagSet(array('flag1'=>$q, 'flag2'=>$p));
$w = new FlagSet(array('flag1'=>$q));
echo "\nComposite objects u(o,p) and v(q,p)\n";
compareObjects($u, $v);
echo "\nu(o,p) and w(q)\n";
compareObjects($u, $w);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Composite objects u(o,p) and v(q,p)
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE
u(o,p) and w(q)
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE
]]>
</screen>
</example>
</para>
</sect1>
</appendix>
<!-- 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:"~/.phpdoc/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
-->
|