פרק 9. Expressions - ביטויים

ביטויים הם אחד מאבני הייסוד הכי חשובים ב PHP. ב PHP, כמעט כל דבר שכותבים הוא ביטוי. הדרך הפשוטה והמדוייקת ביותר להגדיר את המונח "ביטוי" היא "כל דבר שיש לו ערך".

הצורה הבסיסית ביותר של "ביטוים" הם קבועים ומשתנים. כאשר מקלידים "$a = 5", למעשה מציבים את הערך '5' לתוך $a. למספר '5', יש כמובן את הערך 5, או במילים אחרות '5' הוא ביטוי עם הערך 5 (במקרה שלנו, '5' הוא קבוע מסוג מס' שלם ).

אחרי ההצבה הנ"ל, כצפוי הערך של $a's הוא 5. כמו כן, אם ייתכב בתוכנית $b = $a, התוצאה תהיה כאילו נכתב $b = 5. במילים אחרות, $a הוא "ביטוי" עם הערך 5 גם כן.

דוגמאא מעט יותר מורכבת "לביטויים" הם פונקציות. למשל, הבא נבחן את הדוגמא הבאה:

function foo ()
{
    return 5;
}

בהנחה שיש לך היכרות עם הנושא של פונקציות (אם התשובה שלילית תן הצצה בפרק הדן ב"פונקציות"), אתה בטח מניח שהביטוי $c = foo() הוא ביסודו ממש כמו כתיבת $c = 5, וכמבן שאתה צודק. פונקציות הן ביטויים עם הערך שהן עצמן מחזירות. מאחר ו foo() מחזיר את הערך 5, אפשר לאמר שהערך של הפונקציה 'foo()' הוא 5. לרוב, פוקנקציות לא רק מחזירות ערך סטטי, אלא גם מבצעות חישוב כלשהו.

כמבון, ערכים ב PHP לא חייבים להיות integers (מספרים שלמים), ולעיתים קרובות הם לא. PHP תומכת בשלושה ערכים סקאלריים (הסבר בהמשך): מספרים שלמים, ערכי נקודה צפה (מספרים לא שלמים) וערכי מחרוזת (ערכים סקלריים-scalar- הם ערכים שלא ניתן ל"שבור" לחקלים קטנים יותר, להבדיל למשל ממערכים). PHP תומכת כמובן בשני סוגי ערכים מורכבים(non-scalar): מערכים ואובייקטים. כל אחד מסוג ערכים זה יכול להיות מוקצה לתוך משתנה או או להיות מוחזר מתוך פונקציות.

לפי שעה, משתמשים של PHP/FI 2 לא צריכים להרגיש כל שינוי. בכל מקרה, PHP לקחו את "הביטויים" רחוק יותר, ממש כפי שעשו שפות רבות אחרות. PHP היא שפה מונחית ביטויים , מהבחינה שכמעט כל דבר בשפה מבוסס על ביטויים. אפשר לחשוב על על הדוגמא שכבר עסקנו בא, '$a = 5'. קל מאוד לראות שמעורבים בה 2 ערכים, הערך של הקבוע השלם '5', והערך של $a שלמעשה עודכן להיות גם הוא 5. למען האמת יש במקרה הנדון עוד ערך נוסף שמעורב, וההערך הוא ההצבה עצמה. ההצבה עצמה יוצרת ערך גם לערך המוקצה, במקרה הזה 5. למעשה, זה אומר ש '$a = 5', מבלי להתייחס למה שהוא עושה, הוא ביטוי עם הערך 5. לכן, כתיבה של '$b = ($a = 5)' היא כמו כתיבה של '$a = 5; $b = 5;' (הסימן סמיקולו ';' מסמן סיום של משפט הוראה). מאחר וניתוח המשפט נעשה מימין לשמאל, אפשר למעשה גם לכתוב: '$b = $a = 5'.

דוגמא טובה נוספת להסבר צורת קריאת הביטויים: משתמשי PHP/FI 2 ושפות אחרות עשויים להכיר את קיומם של האופרטורים משנתה++ ו משתנה--. אלו הם האופרטורים לקידום ולהחסרה. ב PHP/FI 2, המשפט '$a++' הוא חסר ערך (הוא אינו ביטוי), ולכן אין בו כל שימוש. PHP מגיברה את היכולות של אופרטורי ההגדלה/חיסור על ידי הפיכתם לביטויים, ממש כמו ב C. ב PHP, כמו ב C, ישנם שני סוגים של אופרטורי הגדלה pre-increment ו post-increment. שני אלה בייסודם מגדילים את ערכי המשתנה, והאפקט על המשתנה הוא זהה. ההבדל הוא בערך שך המשתנה המוגדל. Pre-increment, שנכתב כ '++$variable', מגדיל את הערך המוגדל (PHP מגדילה את הערך לפני שהיא קוראת את הערך לכן המונח 'pre-increment' או בתרגום צולע משהו: "מוגדל מראש"). Post-increment, שנכתב כ '$variable++' מציב את הערך המקורי של $variable, לפני שהוא מגדיל אותו (PHP מגדילה את הערך של המשתנה אחרי שקראה את ערכו, לפיכך השם 'post-increment').

סוג מפוף של ביטויים הוא ביטוי השוואה. ביטויים אלו מוערכים כ 0 או 1, כלומר כ FALSE או כ TRUE (בהתאמה). PHP תומכת ב > (גדול מ), >= (גדול או שווה ל), == (שווה), != (לא שווה), < (קטן מ) and <= (קטן או שווה ל). השימוש בביטויים אלו נפוך בעיקר בביצוע משפטי תנאי , מהסוג של if לדוגמא.

הסוג החארון של ביטויים שקיים הוא שילוב של operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.

There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:

$first ? $second : $third

If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.

The following example should help you understand pre- and post-increment and expressions in general a bit better:

function double($i)
{
    return $i*2;
}
$b = $a = 5;        /* assign the value five into the variable $a and $b */
$c = $a++;          /* post-increment, assign original value of $a 
                       (5) to $c */
$e = $d = ++$b;     /* pre-increment, assign the incremented value of 
                       $b (6) to $d and $e */

/* at this point, both $d and $e are equal to 6 */

$f = double($d++);  /* assign twice the value of $d <emphasis>before</emphasis> 
                       the increment, 2*6 = 12 to $f */
$g = double(++$e);  /* assign twice the value of $e <emphasis>after</emphasis>
                       the increment, 2*7 = 14 to $g */
$h = $g += 10;      /* first, $g is incremented by 10 and ends with the 
                       value of 24. the value of the assignment (24) is 
                       then assigned into $h, and $h ends with the value 
                       of 24 as well. */

In the beginning of the chapter we said that we'll be describing the various statement types, and as promised, expressions can be statements. However, not every expression is a statement. In this case, a statement has the form of 'expr' ';' that is, an expression followed by a semicolon. In '$b=$a=5;', $a=5 is a valid expression, but it's not a statement by itself. '$b=$a=5;' however is a valid statement.

One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.

PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.