PHP: V�razy - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links 
search for in the  
previousKonstantyOper�torynext
Last updated: Thu, 21 Nov 2002
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Chinese | Dutch | Finnish | French | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Slovak | Spanish | Swedish | Turkish

Kapitola 10. V�razy

V�razy jsou nejd�le�it�j��mi stavebn�mi kameny PHP. V PHP je t�m�� v�e, co nap�ete, v�raz. Nejjednodu���, a p�ece nejp�esn�j�� definic� v�razu je "v�echno, co m� hodnotu".

Nejz�kladn�j��mi formami v�raz� jsou konstanty a prom�nn�. Kdy� nap�ete "$a = 5", p�i�azujete '5' do $a. '5' m�, pochopiteln�, hodnotu 5, nebo jin�mi slovy, '5' je v�raz s hodnotou 5 (v tomto p��pad� je '5' celo��selnou konstantou).

Po tomto p�i�azen� budete o�ek�vat, �e hodnota $a bude 5, tak�e kdybyste napsali $b = $a, o�ek�vali byste tot�, jako p�i naps�n� $b = 5. Jin�mi slovy, $a je tedy v�raz s hodnotou 5. Pokud v�e pracuje spr�vn�, p�esn� to se tak� stane.

O n�co slo�it�j��m p��kladem v�raz� jsou funkce. Uva�ujme nap�. tuto funkci:

function foo ()
{
    return 5;
}

Za p�edpokladu, �e jste dob�e sezn�meni s konceptem funkc� (pokud ne, nahl�dn�te do kapitoly o funkc�ch), byste p�edpokl�dali, �e naps�n� $c = foo() je v z�sad� tot� jako $c = 5, a m�te pravdu. Funkce jsou v�razy s hodnotou jejich n�vratov� hodnoty. Funkce foo() vrac� 5, tud� hodnota v�razu 'foo()' je 5. Obvykle funkce nevracej� konstantn� hodnotu, n�br� n�co vypo��t�vaj�.

Hodnoty v PHP samoz�ejm� nemusej� b�t pouze cel� ��sla, a velmi �asto tak� nejsou. PHP podporuje t�i typy skal�rn�ch hodnot: celo��seln�, re�ln� (pohybliv� ��dov� ��rka) a �et�zce (skal�rn� hodnoty jsou hodnoty, kter� nejde "rozb�t" na men�� ��sti, narozd�l nap�. od pol�). PHP podporuje tak� dva kompozitn� (neskal�rn�) typy: pole a objekty. Ka�d� z t�chto typ� hodnot m��e b�t p�i�azen do prom�nn� nebo vracen z funkce.

U�ivatel� PHP/FI 2 by nem�li poc�tit zm�nu. Ale PHP jde ve v�razech mnohem d�le, stejn� jako mnoho jin�ch programovac�ch jazyk�. PHP je v�razov� orientovan� jazyk, ve smyslu, �e t�m�� v�e je v�raz. Uva�ujme p��klad, kter�m jsme se ji� zab�vali, '$a = 5'. Ihned vid�me, �e jsou zde zahrnuty dv� hodnoty, celo��seln� konstanta '5' a hodnota $a, kter� je aktualizov�na na 5. Ale je pravda, �e je tu je�t� jedna hodnota, je to hodnota samotn�ho p�i�azen�. P�i�azen� jako takov� ohodnocuje p�i�azovanou hodnotu, v tomto p��pad� 5. V praxi to znamen�, �e '$a = 5', bez ohledu na to co d�l�, je v�raz s hodnotou 5. Proto je '$b = ($a = 5)' tot� jako '$a = 5; $b = 5;' (st�edn�k ozna�uje konec v�razu). Proto�e p�i�ezen� jsou parsov�na zprava doleva, m��ete tak� napsat '$b = $a = 5'.

Jin�m dobr�m p��kladem orientace na v�razy je pre- a post-inkrementace a dekrementace. U�ivatel� PHP/FI 2 a mnoha jin�ch jazyk� znaj� notaci prom�nn�++ a prom�nn�--. To jsou inkrementa�n� a dekrementa�n� oper�tory. V PHP/FI 2 nem�lo '$a++' ��dnou hodnotu (nen� to v�raz), a proto ne�lo p�i�adit nebo jinak pou��t. PHP roz�i�uje schopnosti p�em�nou t�chto konstrukc� ve v�razy, jako v C. V PHP, stejn� jako v C, existuj� dva typy inkrementace - pre-inkrementace a post-inkrementace. Oba ve sv� podstat� inkrementuj� prom�nnou a efekt na tuto prom�nnou je toto�n�. Rozd�l je v hodnot� inkrementa�n�ho v�razu. Pre-inkrementace, zapsan� jako '++$var', ohodnocuje v�raz inkrementovanou hodnotou (PHP inkrementuje prom�nnou d��ve, ne� p�e�te jej� hodnotu, proto "pre-inkrementace"). Post-inkrementace, zapsan� jako '$var++', ohodnocuje v�raz p�vodn� hodnotou prom�nn� $var, p�ed inkrementac� (PHP inkrementuje prom�nnou po p�e�ten� jej� hodnoty, proto "post-inkrement").

Velmi �ast�m typem v�raz� jsou v�razy porovn�vac�. Tyto v�razy se ohodnocuj� 0 a 1 ve v�znamu FALSE, resp. TRUE. PHP podporuje > (v�t�� ne�), >= (v�t�� nebo rovno), == (rovn� se), != (nerovn� se), < (men�� ne�) a <= (men�� nebo rovno). Tyto v�razy se nej�ast�ji pou��vaj� v podm�nk�ch, jako je konstrukt if.

Posledn�m p��kladem v�raz�, kter�m se budeme zab�vat, je kombinac� p�i�azen� a oper�tor�. Ji� v�te, �e kdy� chcete inkrementovat $a o jedni�ku, jednodu�e nap�ete '$a++' nebo '++$a'. Ale co kdy� chcete hodnotu zv��it o jin� ��slo, nap�. o 3? Mohli byste napsat '$a++' v�ckr�t za sebou, ale to samoz�ejm� nen� efektivn� ani pohodln�. Mnohem prakti�t�j�� je napsat '$a = $a + 3'. V�raz '$a + 3' ohodnocuje hodnotu $a plus 3 a je p�i�azen zp�t do $a, co� d�v� $a inkrementovan� o 3. V PHP, stejn� jako v �ad� jin�ch jazyk� (jako je C), to m��ete napsat krat��m zp�sobem, kter� se �asem stane jasn�j�� i rychlej�� k pochopen�. P�i�ten� 3 k aktu�ln� hodnot� $a lze zapsat jako '$a += 3'. P�esn� to znamen� "vezmi hodnotu $a, p�i�ti k n� 3 a p�i�a� zp�t do $a". Krom� krat��ho a p�ehledn�j��ho z�pisu je v�hodou tak� rychlej�� proveden�. Hodnota '$a += 3', jako hodnota regul�rn�ho p�i�azen�, je p�i�azovan� hodnota. Uv�domte si, �e to NEN� 3, n�br� $a plus 3 (co� je hodnota v�razu p�i�azovan�ho do $a). Takto lze pou��t jak�koli bin�rn� oper�tor, nap��klad '$a -= 5' (ode�ti 5 od hodnoty $a), '$b *= 7' (vyn�sob hodnotu $b ��slem 7) apod.

Je tu je�t� jeden v�raz, kter� se m��e zd�t zvl�tn�, pokud jste ho je�t� nevid�li v jin�ch jazyc�ch: tern�rn� podm�n�n� oper�tor:

$prvni ? $druhy : $treti

Pokud hodnota prvn�ho podv�razu je TRUE (nenulov�), je ohodnocen druh� podv�raz a je v�sledkem cel�ho podm�n�n�ho v�razu. Jinak je ohodnocen t�et� podv�raz a je pak hodotou cel�ho v�razu.

N�sleduj�c� p��klad by m�l pomoci l�pe pochopit pre- a post-inkrementaci i v�razy obecn�:

function double($i)
{
    return $i*2;
}
$b = $a = 5;        /* p�i�a� hodnotu p�t do prom�nn�ch $a a $b */
$c = $a++;          /* prove� post-inkrement, p�i�a� p�vodn� hodnotu $a 
                       (5) do $c */
$e = $d = ++$b;     /* prove� pre-inkrement, p�i�a� inkrementovanou hodnotu 
                       $b (6) do $d a $e */

/* nyn� jsou hodnoty prom�nn�ch $d a $e rovny 6 */

$f = double($d++);  /* p�i�a� dvakr�t hodnotu $d <emphasis>p�ed</emphasis> 
                       inkrementac�, 2*6 = 12, do $f */
$g = double(++$e);  /* p�i�a� dvakr�t hodnotu $e <emphasis>po</emphasis>
                       inkrementaci, 2*7 = 14 do $g */
$h = $g += 10;      /* nejd��ve je $g inkrementov�no o 10 m� pak hodnotu 24. 
                       Hodnota p�i�azen� (24) se p�i�ad� do $h a $h t�m
                       z�sk�v� tak� hodnotu 24. */

Na za��tku kapitoly bylo �e�eno, �e si pop�eme r�zn� typy konstrukt�, a jak bylo sl�beno, v�razy mohou b�t konstrukty. V tomto p��pad� maj� konstrukty form�t 'expr' ';', co� znamen� "v�raz n�sledovan� st�edn�kem. V konstruktu '$b=$a=5;', je $a=5 platn� v�raz, ale samo o sob� to nen� konstrukt.'$b=$a=5;' je i platn� konstrukt.

Pozn. p�ekladatele: P�edchoz�m odstavci (ob�as i jinde) pou��v�m term�n "konstrukt" pro anglick� slovo "statement". Tento p�eklad nen� p��li� korektn�, ale v �esk� program�torsk� mluv� neexistuje vhodn� term�n. Kdyby n�kdo v�d�l o lep��m, napi�te mi, pros�m, na [email protected].

Posledn� v�c�, kter� si zaslou�� zm�nku, je pravdivostn� hodnota v�raz�. V mnoha p��padech, hlavn� podm�nk�ch a cyklech, v�s nezaj�m� konkr�tn� hodnota v�razu, n�br� pouze to, jestli je TRUE nebo FALSE. Konstanty TRUE a FALSE (mal�/velk� p�smena nehraj� roli) p�edstavuj� dv� mo�n� boolovsk� (pravdivostn�) hodnoty. V p��pad� pot�eby je v�raz automaticky p�eveden na typ boolean. Detailn�j�� informace o zp�sobu konverze - viz sekce o typov� konverzi.

PHP poskytuje plnou a silnou implementaci v�raz� a �pln� je zdokumentovat p�esahuje rozsah tohoto manu�lu. V��e uveden� p��klady by v�m m�li nazna�it, co jsou v�bec v�razy a jak konstruovat u�ite�n� v�razy. Ve zb�vaj�c� ��sti manu�lu budeme ps�t expr jako�to jak�koli platn� PHP v�raz.

User Contributed Notes
V�razy
add a note about notes
rlynch at ignitionstate dot com
29-Sep-1999 09:43

boolean expressions short-circuit, currently.
If boolean expression short-circuiting is a feature rather than a coincidence, it should probably be added here... Unless I missed it.

anthony at n dot o dot s dot p dot a dot m dot trams dot com
24-Nov-2000 06:01

The ternary conditional operator is a useful way of avoiding inconvenient if statements.  They can even be used in the middle of a string concatenation, if you use parentheses.  

Example:

if ( $wakka ) {
 $string = 'foo' ;
} else {
 $string = 'bar' ;
}

The above can be expressed like the following:

$string = $wakka ? 'foo' : 'bar' ;

If $wakka is true, $string is assigned 'foo', and if it's false, $string is assigned 'bar'.

To do the same in a concatenation, try:

$string = $otherString . ( $wakka ? 'foo' : 'bar' ) ;

mircho at _NO_SPAM_abv dot bg
23-Jan-2001 07:23

try this

$a = "-1";
$a++;
echo $a;

this prints -2 as a result

to be sure you get what you wanted to get just do this

$a = "-2"
$b = (integer)($a)
and now $b will behave

somebody mentioning strict typing?

yasuo_ohgaki at hotmail dot com
12-Mar-2001 06:14

Manual defines "expression is anything that has value", Therefore, parser will give error for following code.

($val) ? echo('true') : echo('false');
Note: "? : " operator has this syntax  "expr ? expr : expr;"

since echo does not have(return) value and ?: expects expression(value).

However, if function/language constructs that have/return value, such as include(), parser compiles code.

Note: User defined functions always have/return value without explicit return statement (returns NULL if there is no return statement). Therefore, user defined functions are always valid expressions.
[It may be useful to have VOID as new type to prevent programmer to use function as RVALUE by mistake]

For example,

($val) ? include('true.inc') : include('false.inc');

is valid, since "include" returns value.

The fact "echo" does not return value(="echo" is not a expression), is less obvious to me.

Print() and Echo() is NOT identical since print() has/returns value and can be a valid expression.

tmacamNOSP at Mufc dot br
13-Sep-2001 06:57

As reported previously, PHP boolean operators seem to short-circuit. What if you want them to do not short-circuit?

Exemple:
$result_of = f1() and f2() and f3()

suppose you want to run f3 even when f1 already returned false.

If you perform some silly tests such as:
echo true + true;
you'll see that indeed, true=1 and false=0 and true+true = 2 (ok. this _is_ silly!)

Anyway, the point is: you could use * (multiplication) instead of 'and', to get a not short-circuiting 'and' and + (sum) to get a not short-circuiting or.


[]s
MaCa

08-Mar-2002 08:20
I found this worked nicely:

echo $var ? "yup" : "nope";

This doesnt work:

echo $var ? "yup";

you need to go:

echo $var ? "yup" : "";

-- there is not space in "", but it may appear that way above

Mattias at mail dot ee
25-May-2002 10:29

A note about the short-circuit behaviour of the boolean operators.

1. if (func1() || func2())
Now, if func1() returns true, func2() isn't run, since the expression
will be true anyway.

2. if (func1() && func2())
Now, if func1() returns false, func2() isn't run, since the expression
will be false anyway.

The reason for this behaviour comes probably from the programming
language C, on which PHP seems to be based on. There the
short-circuiting can be a very useful tool. For example:

int * myarray = a_func_to_set_myarray(); // init the array
if (myarray != NULL && myarray[0] != 4321) // check
myarray[0] = 1234;

Now, the pointer myarray is checked for being not null, then the
contents of the array is validated. This is important, because if
you try to access an array whose address is invalid, the program
will crash and die a horrible death. But thanks to the short
circuiting, if myarray == NULL then myarray[0] won't be accessed,
and the program will work fine.

toreilly at cityspree dot com
27-May-2002 09:30

I actually find the short-circuit aspect of expressions useful.  As in:
if ($foo AND Bar()) { echo "OK"; }

where Bar() should only be run if $foo is set, and OK should only be printed if both evaluate to TRUE.

My only concern is if this is the intended result in PHP.  In other words, if I code this way will it fail under later releases of PHP?

tai at iij dot ad dot jp
30-May-2002 02:30

Regarding short-circuit expression, it is a frozen feature, not a coincidence. At least, that's what I read from the URL below.



Now, I sometimes feel the need for BNF-written document to explain PHP syntax to others...does anyone know where I can find one?

iamfast at tampabay dot rr dot com
16-Jul-2002 08:47

If you need to do something like make sure you dont say '1 days' try this

echo $being-$today.' day'.($begin-$today===1?'':'s').' untill XYZ';

php at cotest dot com
17-Jul-2002 06:08

It should probably be mentioned that the short-circuiting of expressions (mentioned in some of the comments above) is often called "lazy evaluation" (in case someone else searches for the term "lazy" on this page and comes up empty!).
oliver at hankeln-online dot de
07-Aug-2002 01:06

The short-circuiting IS a feature. It is also available in C, so I suppose the developers won�t remove it in future PHP versions.

It is rather nice to write:

$file=fopen("foo","r") or die("Error!");

Greets,
Oliver

add a note about notes
previousKonstantyOper�torynext
Last updated: Thu, 21 Nov 2002
show source | credits | stats | mirror sites
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Thu Nov 28 00:09:23 2002 CET