barak Fri Jan 25 19:54:53 2002 EDT Added files: /phpdoc/he/language oop.xml Log: initial of translating this file
Index: phpdoc/he/language/oop.xml +++ phpdoc/he/language/oop.xml <?xml version="1.0" encoding="iso-8859-1"?> <!-- $Revision: 1.1 $ --> <chapter id="language.oop"> <title>Classes and Objects</title> <sect1 id="keyword.class"> <title><literal>מחלקות</literal></title> <para> מחלקה היא אוסף של משתנים ופונקציות שעובדות עם משתנים אלו. מחלקה מוגדרת תוך שימוש בתחביר הבא: <informalexample> <programlisting role="php"> <![CDATA[ <?php class Cart { var $items; // הגדרת משתנה של המחלקה בשם $items // 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; } else { return false; } } } ?> ]]> </programlisting> </informalexample> </para> <para> בדוגמא הנ"ל, הוגדרה מחלקה ששמה Cart, שמורכבת ממערך המשוייך לפריטים שבתוך בסל (Cart), ומשני פונקציות להוספה (add) ולהסרה (remove) של פריטים מתוך העגלה. </para> <caution> <simpara> המדריך הבא מתאים ל PHP4 !. </simpara> <simpara> המילה <literal>stdClass</literal> היא מילה שמורה הנמצאת בשימוש פנימי על ידי ZEND. לכן, אין להשתמש במילה <literal>stdClass</literal> ב PHP. </simpara> <simpara> שם הפונקציה <literal>__sleep</literal> ושם הפונקציה <literal>__wakeup</literal> בעלות שימוש מיוחד ב - php. אתב לא יכול להשתמש בשם הזהה לאחת משתי הפונקציות הנ"ל במחלקה כלשהי אלא אם אתה רוצה להשתמש בהן לאפשרות המיוחדת (שתפורט בהמשך) שלה הן נועדו. ראה בהמשך המדריך למידע נוסף. </simpara> <simpara> כל פונקציות ה PHP המופלאות (בהמשך יפורט מידע נוסף בנושא) מתחילות עם __. מומלץ מאוד לא לקרוא לשמות פונקציה ב PHP עם שם המתחיל ב __ אלא אם אתה רוצה לתעד אותן כפונקציות "קסומות". </simpara> </caution> <note> <simpara> ב PHP 4, איתחול משתני מחלקה שהוגדרו בעזרת <literal>var</literal> אפשרי רק עם קבועים. כדי לאתחל משתנים, שלא על ידי ערכי קבועים, אתה צריך להשתמש בפונקציה שנקראת אוטומטית על ידי PHP כאשר נוצר אובייקט חדש של הפונקציה. פונקציה כזאת נקראת "פונקציה בנאית" (constructor) (ראה למטה). </simpara> <informalexample> <programlisting role="php"> <![CDATA[ <?php /* במחלקה הבאה, תגרור הודעת שגיאה בגלל איתחול משתנים שגוי ! */ class Cart { var $todays_date = date("Y-m-d"); var $name = $firstname; var $owner = 'Fred ' . 'Jones'; var $items = array("VCR", "TV"); } /* ככה זה אמור להעשות: */ class Cart { var $todays_date; var $name; var $owner; var $items; function Cart() // הבנאי של המחלקה { $this->todays_date = date("Y-m-d"); $this->name = $GLOBALS['firstname']; /* etc. . . */ } } ]]> </programlisting> </informalexample> </note> <para> מחלקות הן תבניות, כלומר, הן הכנה ליצירת משתנים אמיתיים (האובייקטים) יוצרים את המשתנים מהסוג המבוקש תוך שימוש באופרטור <literal>new</literal>. </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> הדוגמא הנ"ל יצרה את האובייקטים $cart ו $another_cart, שניהם אובייקטים שנוצרו מהמחלקה Cart. הפונקציה add_item() של האובייקט - $cart נקראת על מנת להוסיף פריט אחד של חפץ מס' 10 לתוך העגלה. 3 פריטים חפץ מס' 0815 נוספו לאובייקט $another_cart. </para> <para> גם ל $cart וגם ל $another_cart, יש את הפונקציות add_item(), remove_item() ומשתנה של פריטים ($items) . אלו הם פונקציות ומשתנים נפרדים. אפשר לחשוב על אובייקטים כדומים לספריות וקבצים במערכת קבצים. בתוך מערכת קבצים יכולים להיות לך שני קבצי README.TXT שונים לחלוטין, כל עוד הם יימצאו בספריה אחרת. ממש כמו במערכות קבצים, כשצריך להלקיד את המסלול המלא על מנת להפעיל קובץ כלשהו, אם לא נמצאים בספריה שלו, יש צורך לתת את השם המלא של הפונקציה אותה רוצים להפיל, במונחים של php: "רמת הגובה" של האובייקט נקבע בעזרת שמות שהוגדרו, ומהפריד בין שמות אלו ->. לכן, המילים $cart->items ו $another_cart->items הן שמות של שתי משתנים אחרים. יש לשים לב לעובדה שהמשתנה נקרא $cart->items, ולא $cart->$items, וזאת בשל, שלשם משתנה ב PHP יש רק סימן $ אחד. </para> <informalexample> <programlisting role="php"> <![CDATA[ // correct, single $ $cart->items = array("10" => 1); // שגוי, בגלל ש $cart->$items הופך להיות $cart->"" $cart->$items = array("10" => 1); //נכון, אבל עלול להיות גם משהו שלא אליו התכוונו //$cart->$myvar הפך להיות $cart->items $myvar = 'items'; $cart->$myvar = array("10" => 1); ]]> </programlisting> </informalexample> <para> עם הגדרת המחלקה, אין אפשרות לדעת אילו שמות אובייקטים ייוצרו בתוכנית לאותה מחלקה: בזמן שהמחלקה Cart נכתבה, לא היה ידוע שייוצר האובייקט $cart או האובייקט $another_cart מאוחר יותר. לכן, בלתי אפשרי לכתוב $cart->items בתוך המחלקה Cart עצמה. במקום זאת, כדי שאפשר יהיה לפנות בתוך לתוך הפונקציות והמשתנים של האוייקט בתוך המחלקה עצמה, אפשר להשתמש ב בפסאודו - משתנה (משתנה מדומה) $this שיכול להחשב כ 'של עצמי' או 'אובייקט נוכחי'. לפיכך, '$this->items[$artnr] += $num' יכול להקרא כ 'הוסף $num למונה $artnr של מערל החפצים של עצמי' או 'הוסף $num למונה $artnr של מערך החפצים שנמצא בתוך האובייקט הנוכחי'. </para> </sect1> <sect1 id="keyword.extends"> <title><literal>הורשות</literal></title> <para> לעיים קרובות, זקוקים למחלקות עם עם משתנים ופונקציות דומות למשתנים ומחלקות בפונקציות אחרות. למעשה, זה נוהג טוב להגדיר מחלקה כללית שיכולה לשמש אותך בכל הפרוייקטים שלך ולהתאים את מחלקה זאת לצרכי כל אחד מהפרוייקטים ספציפת. לסייע בזאת, מחלקות יכולות להיות הרחבות של מחלקות אחרות. למחלקה שמרחיבה או היורשת יש את כל המשתנים והפונקציות של המחלקה הבסיסית (זה נקרא 'ירושה' למרות העובדה שאף אחד לא מת) וכן את מה שאתה מוסיף לה (פונקציות ומשתנים נוספים) זה בלתי אפשרי לבטל הגדרה של משתנה או פונקציה כלשהי במחלקה. מחלקה מרחיבה, נשענת לעולם על בסיס של מחלקה אחת בלבד,וזאת בגלל, שהורשה מרובה לא נתמכת. מחלקות מורחבות תוך שימוש במילה השמורה 'extends'. </para> <informalexample> <programlisting role="php"> <![CDATA[ class Named_Cart extends Cart { var $owner; function set_owner ($name) { $this->owner = $name; } } ]]> </programlisting> </informalexample> <para> בדוגמא הנ"ל הוגדרה מחלקה Named_Cart שיש לה את כל הפונקציות והמשתנים של Cart בנוסף למשתנה $owner ולפנוקציה נוספת בשם set_owner(). יוצרים את העדלה בדרך הרגילה, אלא שאפר גם לקבוע ערכים ולקרוא את הערכים של בעל העגלה. עדיין אפשר להשתמש פונקציות הרגילות של העגלה. </para> <informalexample> <programlisting role="php"> <![CDATA[ $ncart = new Named_Cart; // יצירת אובייקט $ncart->set_owner("kris"); // הכנסת שם של בעלים לאותה עגלה print $ncart->owner; // הצגה של ערך הבעלים של העגלה $ncart->add_item("10", 1); // שימוש בפונקציה שהורשנו מתוך cart ]]> </programlisting> </informalexample> </sect1> <sect1 id="language.oop.constructor"> <title><literal>Constructors</literal></title> <caution> <simpara> ב PHP 3 ו PHP 4 לפונקציות הבנאיות מתנהגות בצורה שונה. הסמנטיקה של PHP 4 עדיפה בהרבה. </simpara> </caution> <para> בנאים הם פונקציות במחלקה שמופעלים אוטומטית כשיוצרים מופע חדש של המחלקה (בעת יצירת אובייקט חדש) תוך שימוש במילה <literal>new</literal>. ב PHP 3, פונקציות מוגדרות כבנאיות כשהן נקראות בשם הזהה לשם המחלקה. ב PHP 4, פונקציות משמשות כבנאיות, כשהן בעלות אותו שם של מחלקה שהן מוגדרות בתוכן - ההבדל הוא לכאורה קטן, אבל קריטי (ראה למטה). </para> <informalexample> <programlisting role="php"> <![CDATA[ // עובד ב PHP 3 וגם ב PHP 4. class Auto_Cart extends Cart { function Auto_Cart() { $this->add_item ("10", 1); } } ]]> </programlisting> </informalexample> <para> בודגמא הוגדרה מחלקה Auto_Cart שהיא Cart ובנוסף לה בנאי שמאתחל את העגלה עם ריט אחד של מוצר שמספרו "10" בכל פעם שיוצרים מופע חדש של Auto_Cart בעזרת "new". הפנקציה הבנאית יכולה לקחת ארגומנטים שהם אופציונליים, מה שגורם להם להיות שימושיים במיוחד. על מנת שאפשר יהיה להשתמש בפונקציה בלי פרמטרים, כל הפרמטרים שמועברים לבנאי צריכם להקבע אופציונלית על ידי אספקת ערכי ברירת מחדל. </para> <informalexample> <programlisting role="php"> <![CDATA[ // עובד גם ב PHP 3 וגם ב PHP 4. 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> <caution> <simpara> ב PHP 3, למחלקות ובנאים נגזרים יש כמה מגבלות. הדוגמא הבאה צריכה להקרא בזהירות על מנת שההגבלות יהיו מובנות. </simpara> </caution> <informalexample> <programlisting role="php"> <![CDATA[ class A { function A() { echo "I am the constructor of A.<br>\n"; } } class B extends A { function C() { echo "I am a regular function.<br>\n"; } } // no constructor is being called in PHP 3. $b = new B; ]]> </programlisting> </informalexample> <para> ב PHP 3, שום פונקציה בנאית לא נקרא בדוגמא הנ"ל. החוק ב PHP 3 הוא: 'הבנאי A הוא הפונקציה של אותו שם של המחלקה.'. השם של המחלקה הוא B, ואין שום פונקציה שנקראת B() במחלקה B. לכן כלום לא קורה. </para> <para> עניין זהב תוקן ב PHP 4 על ידי הכללת חוק חדש: אם למחלקה אין פונקציה בנאית, הפונקציה בנאית של מחלקת הבסיס נקראת, אם היא קיימת. בדוגמא מעל, ב PHP4 בעת יצירת האוייבקט יודפס הפלט: 'I am the constructor of A.<br>'. </para> <informalexample> <programlisting role="php"> <![CDATA[ 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 { function C() { echo "I am a regular function.<br>\n"; } } // This will call B() as a constructor. $b = new B; ]]> </programlisting> </informalexample> <para> ב PHP 3, הפונקציה B() שבמחלקה A לפתע תהפוך לבנאית במחלקה B, למרות שלא לזה "התכוון המשורר". החוק ב PHP 3 הוא: 'הבנאי A היא הפונקציה בעלת אותו שם של המחלקה.'.ל PHP 3 לא איכפת אם הפונקציה הוגדרה במחלקה B, או הם היא נגזרה ממחלקה A . </para> <para> גם עניין זה תוקן ב PHP 4 על ידי יצירת החוק הבא: 'הפונקציה הנבאית A היא פונקציה בעלת אות שם של המחלקה שהיא מוגדרת בתוכה. 'לכן ב PHP 4, המחלקה B שאין לה את הבנאית של עצמה תשתמש בפונקציה הבנאית של מחלקת הבסיס, ולפיכך יודפס על המסך 'I am the constructor of A.<br>'. </para> <caution> <simpara> לא PHP 3 ולא PHP 4 קוראים לבנאי של מחלקת הבסיס אוטומטית מבנאי של מחלקה נגזרת. זה באחריות המשתמש לקורא לפונקציה הבנאית של מחלקת הבסיס במקרה כזה. </simpara> </caution> <note> <simpara> אין "פונקציה הורסת" (destructors) ב PHP 3 או PHP 4. אתה יכול להשתמש ב <function>register_shutdown_function</function> במקום זאת לדמות את רוב האספקטים של "פונקציה הורסת" (ההפיך מבנאית). </simpara> </note> <para> "פונקציה הורסת" היא פונקציה שנקראת אוטמטית כאשר "משמידים" אובייקט, אם על ידי שימוש ב <function>unset</function> ואם פשוט על ידי יציאה מחוץ לתחום של האובייקט. כמו שנאמר, אין פונקציות מסוג זה ב PHP. </para> </sect1> <sect1 id="keyword.paamayim-nekudotayim"><!-- :-) --> <title><literal>::</literal></title> <caution> <simpara> הקטע הבא תקף ל PHP 4 בלבד. </simpara> </caution> <para> לעיתים זה שימושי להתייחס ל functions and variables in base classes or to refer to functions in classes that have not yet any instances. The :: operator is being used for this. </para> <informalexample> <programlisting role="php"> <![CDATA[ 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 example() in class A, but there is no object of class A, so that we cannot write $a->example() or similar. Instead we call example() 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 no use $this at all. </para> <para> In the above example, class B redefines the function example(). The original definition in class A is shadowed and no longer available, unless you are refering specifically to the implementation of example() in class A using the ::-operator. Write A::example() to do this (in fact, you should be writing parent::example(), 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 $this and object variables. </para> </sect1> <sect1 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> declation 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[ 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 id="language.oop.serialization"> <title>Serializing objects - objects in sessions</title> <note> <simpara> In PHP 3, objects will lose their class association throughout the process of serialization and unserialization. The resulting variable is of type object, but has no class and no methods, thus it is pretty useless (it has become just like an array with a funny syntax). </simpara> </note> <caution> <simpara> The following information is valid for PHP 4 only. </simpara> </caution> <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 $a of class A on page1.php and serialize this, you'll get a string that refers to class A and contains all values of variabled contained in $a. If you want to be able to unserialize this on page2.php, recreating $a of class A, the definition of class A must be present in page2.php. This can be done for example by storing the class defintion of class A in an include file and including this file in both page1.php and page2.php. </para> <informalexample> <programlisting role="php"> <![CDATA[ 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"); fputs($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 <literal>stdClass</literal> without any functions available at all, that is, it will become quite useless. </para> <para> So if in the example above $a 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 page1.php and page2.php. </para> </sect1> <sect1 id="language.oop.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. </para> <para> The intended use of <literal>__sleep</literal> is to close any database connections that object may have, committing 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 id="language.oop.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[ 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[ $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 "new" 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[ // 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[ 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 undestand 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(); /* output: class A: 10 class B: 10 class B: 10 class A: 11 class B: 11 class B: 11 */ ]]> </programlisting> </informalexample> </para> </sect1> </chapter> <!-- 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 -->