Выражения

Выражения - это краеугольный камень PHP. Почти все, что вы пишите в PHP, является выражением. Самое простое и точное определение выражения - "все что угодно, имеющее значение".

Основными формами выражений являются константы и переменные. Если вы записываете "$a = 5", вы присваиваете '5' переменной $a. '5', очевидно, имеет значение 5 или, другими словами, '5' это выражение со значением 5 (в данном случае '5' это целочисленная константа).

После этого присвоения вы ожидаете, что значением $a также является 5, поэтому, если вы написали $b = $a, вы полагаете, что работать это будет так же, как если бы вы написали $b = 5. Другими словами, $a это также выражение со значением 5. Если все работает верно, то именно так и произойдет.

Немного более сложными примерами выражений являются функции. Например, рассмотрим следующую функцию:

<?php
function foo ()
{
    return 
5;
}
?>

Исходя из того, что вы хорошо знакомы с концепцией функций (если нет, то прочитайте главу о функциях), вы полагаете, что запись $c = foo() абсолютно эквивалента записи $c = 5, и вы правы. Функции - это выражения, значением которых является то, что возвращает функция. Поскольку foo() возвращает 5, значением выражения 'foo()' является 5. Как правило, функции возвращают не просто статическое значение, а что-то вычисляют.

Разумеется, значения в PHP не обязаны быть целочисленными, и очень часто ими не являются. PHP поддерживает три типа скалярных значений: целочисленные, с плавающей точкой и строковые значения (скалярными являются значения, которые вы не можете 'разбить' на меньшие части, в отличие, например, от массивов). PHP поддерживает также два комбинированных (не скалярных) типа: массивы и объекты. Каждый из этих типов значений может присваиваться переменной или возвращаться функцией.

До сих пор пользователи PHP/FI 2 не должны были почувствовать каких-либо изменений. Однако PHP, как и многие другие языки, понимает гораздо больше выражений. PHP - это язык, ориентированный на выражения и рассматривающий почти все как выражение. Вернемся к примеру, с которым мы уже имели дело: '$a = 5'. Легко заметить, что здесь присутствуют два значения - значение целочисленной константы '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. Также как и C, PHP поддерживает два типа инкремента - префиксный и постфиксный. Они оба инкрементируют значение переменной и эффект их действия на нее одинаков. Разница состоит в значении выражения инкремента. Префиксный инкремент, записываемый как '++$variable', вычисляется в инкрементированное значение (PHP инкрементирует переменную перед тем как прочесть ее значение, отсюда название 'пре-инкремент'). Постфиксный инкремент, записываемый как '$variable++', вычисляется в первоначальное значение переменной $variable перед ее приращением (PHP инкрементирует переменную после прочтения ее значения, отсюда название 'пост-инкремент').

Очень распространенным типом выражений являются выражения сравнения. Они вычисляются в 0 или 1, означающих соответственно FALSE (ложь) или TRUE (истину). PHP поддерживает > (больше), >= (больше либо равно), == (равно), != (не равно), < (меньше) и <= (меньше либо равно). Он также поддерживает операторы строгого равенства: === (равно и одного типа) и !== (не равно или не одного типа). Чаще всего эти выражения используются в условиях выполнения операторов, таких как if.

Последний пример выражений, который мы здесь рассмотрим, это смешанные выражения операции и присвоения. Вы уже знаете, что если вы хотите увеличить $a на 1, вы можете просто написать '$a++' или '++$a'. Но что, если вы хотите прибавить больше, чем единицу, например, 3? Вы могли бы написать '$a++' много раз, однако, очевидно это не очень рациональный или удобный способ. Гораздо более распространенной практикой является запись вида '$a = $a + 3'. '$a + 3' вычисляется в значение $a плюс 3 и снова присваивается $a, увеличивая в результате $a на 3. В PHP, как и в некоторых других языках, таких как C, вы можете записать это более коротким образом, что увеличит очевидность смысла и быстроту понимания кода по прошествии времени. Прибавить 3 к текущему значению $a можно с помощью записи '$a += 3'. Это означает дословно "взять значение $a, прибавить к нему 3 и снова присвоить его переменной $a". Кроме большей понятности и краткости, это быстрее работает. Значением '$a += 3', как и обычного присвоения, является присвоенное значение. Обратите внимание, что это НЕ 3, а суммированное значение $a плюс 3 (то, что было присвоено $a). Таким образом может использоваться любой двухместный оператор, например, '$a -= 5' (вычесть 5 из значения $a), '$b *= 7' (умножить значение $b на 7) и т.д.

Существует еще одно выражение, которое может выглядеть необычным, если вы не встречали его в других языках - тернарный условный оператор:

<?php
$first 
$second $third
?>

Если значением первого подвыражения является TRUE (не ноль), выполняется второе подвыражение, которое и будет результатом условного выражения. В противном случае, будет выполнено третье подвыражение и его значение будет результатом.

Следующий пример должен помочь вам немного улучшить понимание префиксного и постфиксного инкремента и выражений:

<?php
function double($i)
{
    return 
$i*2;
}
$b $a 5;        /* присвоить значение пять переменным $a и $b */
$c $a++;          /* постфиксный инкремент, присвоить значение $a 
                       (5) переменной $c */
$e $d = ++$b;     /* префиксный инкремент, присвоить увеличенное
                       значение $b (6) переменным $d и $e */

/* в этой точке и $d, и $e равны 6 */

$f double($d++);  /* присвоить удвоенное значение $d перед
                       инкрементом (2*6 = 12) переменной $f */
$g double(++$e);  /* присвоить удвоенное значение $e после
                       инкремента (2*7 = 14) переменной $g */
$h $g += 10;      /* сначала переменная $g увеличивается на 10,
                       приобретая, в итоге, значение 24. Затем значение
                       присвоения (24) присваивается переменной $h,
                       которая в итоге также становится равной 24. */
?>

Некоторые выражения могут рассматриваться как инструкции. В данном случае инструкция имеет вид 'выражение' ';' - выражение с последующей точкой с запятой. В записи '$b=$a=5;', $a=5 - это верное выражение, но само по себе не инструкция. Тогда как '$b=$a=5;' является верной инструкцией.

Последнее, что стоит упомянуть, это истинность значения выражений. Во многих случаях, как правило, в условных операторах и циклах, вас может интересовать не конкретное значение выражения, а только значат ли они TRUE или FALSE. Константы TRUE и FALSE (регистро-независимые) - это два возможных булевых значения. При необходимости выражение автоматически преобразуется в булев тип. Подробнее о том, как это происходит, смотрите в разделе о приведении типов.

PHP предоставляет полную и мощную реализацию выражений, и их полное документирование выходит за рамки этого руководства. Вышеприведенные примеры должны дать вам представление о том, что они из себя представляют и как вы сами можете создавать полезные выражения. Далее, для обозначения любого верного выражения PHP в этой документации мы будем использовать сокращение expr.

Коментарии

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

<?php
($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,

<?php
($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.
2001-03-12 01:14:08
http://php5.kiev.ua/manual/ru/language.expressions.html
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.
2002-05-25 06:29:35
http://php5.kiev.ua/manual/ru/language.expressions.html
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
2002-08-07 09:06:09
http://php5.kiev.ua/manual/ru/language.expressions.html
Автор:
An easy fix (although intuitively tough to do...) is to reverse the comparison.

if (5 == $a) {}

If you forget the second '=', you'll get a parse error for trying to assign a value to a non-variable.
2007-02-14 18:56:02
http://php5.kiev.ua/manual/ru/language.expressions.html
It is worthy to mention that:

$n = 3;
$n * --$n

WILL RETURN 4 instead of 6.

It can be a hard to spot "error", because in our human thought process this really isn't an error at all! But you have to remember that PHP (as it is with many other high-level languages) evaluates its statements RIGHT-TO-LEFT, and therefore "--$n" comes BEFORE multiplying, so - in the end - it's really "2 * 2", not "3 * 2".

It is also worthy to mention that the same behavior will change:

$n = 3;
$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

So, if you ever find yourself on a 'wild goose chase' for a bug in that "impossible-to-break, so-very-simple" piece of code that uses pre-/post-'s, remember this post. :)

(just thought I'd check it out - turns out I was right :P)
2007-04-04 10:45:00
http://php5.kiev.ua/manual/ru/language.expressions.html
Автор:
reply to egonfreeman at gmail dot com
04-Apr-2007 07:45 

the second example u mentioned as follow:
=====================================

$n = 3;
$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

===========================================

everything works correctly but one sentence should be modified:

"from 3 * 3 into 3 * 4"  should be "from 3 * 3 into 4 * 3"

best regards~ :)
2007-08-23 04:42:02
http://php5.kiev.ua/manual/ru/language.expressions.html
Regarding the ternary operator, I would rather say that the best option is to enclose all the expression in parantheses, to avoid errors and improve clarity:

<?php
   
print ( $a "many" "just one" );
?>

PS: for php, C++, and any other language that has it.
2007-10-20 11:41:35
http://php5.kiev.ua/manual/ru/language.expressions.html
To jvm at jvmyers dot com:
Your first two if statements just check if there's anything in the string, if you wish to actually execute the code in your string you need eval().
2008-03-16 06:52:30
http://php5.kiev.ua/manual/ru/language.expressions.html
Note that even though PHP borrows large portions of its syntax from C, the ',' is treated quite differently. It's not possible to create combined expressions in PHP using the comma-operator that C has, except in for() loops.

Example (parse error):

<?php

$a 
2$b 4;

echo 
$a."\n";
echo 
$b."\n";

?>

Example (works):
<?php

for ($a 2$b 4$a 3$a++)
{
  echo 
$a."\n";
  echo 
$b."\n";
}

?>

This is because PHP doesn't actually have a proper comma-operator, it's only supported as syntactic sugar in for() loop headers. In C, it would have been perfectly legitimate to have this:

int f()
{
  int a, b;
  a = 2, b = 4;

  return a;
}

or even this:

int g()
{
  int a, b;
  a = (2, b = 4);

  return a;
}

In f(), a would have been set to 2, and b would have been set to 4.
In g(), (2, b = 4) would be a single expression which evaluates to 4, so both a and b would have been set to 4.
2009-04-16 11:04:29
http://php5.kiev.ua/manual/ru/language.expressions.html
evaluation order of subexpressions is not strictly defined for all operators

<?php
function a() {echo 'a';}
function 
b() {echo 'b';}
a() == b(); // outputs "ab", ie evaluates left-to-right

$a 3;
var_dump$a == $a ); // outputs bool(true), ie evaluates right-to-left
?>

this is not a bug: "we [php developers] make no guarantee about the order of evaluation".
See https://bugs.php.net/bug.php?id=61188
2012-02-26 21:29:55
http://php5.kiev.ua/manual/ru/language.expressions.html
Note that there is a difference between a function and a function call, and both
are expressions. PHP has two kinds of function, "named functions" and "anonymous
functions". Here's an example with both:

<?php
// A named function. Its name is "double".
function double($x) {
  return 
$x;
}

// An anonymous function. It has no name, in the same way that the string
// "hello" has no name. Since it is an expression, we can give it a temporary
// name by assigning it to the variable $triple.
$triple = function($x) {
  return 
$x;
};
?>

We can "call" (or "run") both kinds of function. A "function call" is an
expression with the value of whatever the function returns. For example:

<?php
// The easiest way to run a function is to put () after its name, containing its
// arguments (if any)
$my_numbers = array(double(5), $triple(5));
?>

$my_numbers is now an array containing 10 and 15, which are the return values of
double and $triple when applied to the number 5.

Importantly, if we *don't* call a function, ie. we don't put () after its name,
then we still get expressions. For example:

<?php
$my_functions 
= array('double'$triple);
?>

$my_functions is now an array containing these two functions. Notice that named
functions are more awkward than anonymous functions. PHP treats them differently
because it didn't use to have anonymous functions, and the way named functions
were implemented didn't work for anonymous functions when they were eventually
added.

This means that instead of using a named function literally, like we can with
anonymous functions, we have to use a string containing its name instead. PHP
makes sure that these strings will be treated as functions when it's
appropriate. For example:

<?php
$temp     
'double';
$my_number $temp(5);
?>

$my_number will be 10, since PHP has spotted that we're treating a string as if
it were a function, so it has looked up that named function for us.

Unfortunately PHP's parser is very quirky; rather than looking for generic
patterns like "x(y)" and seeing if "x" is a function, it has lots of
special-cases like "$x(y)". This makes code like "'double'(5)" invalid, so we
have to do tricks like using temporary variables. There is another way around
this restriction though, and that is to pass our functions to the
"call_user_func" or "call_user_func_array" functions when we want to call them.
For example:

<?php
$my_numbers 
= array(call_user_func('double'5), call_user_func($triple5));
?>

$my_numbers contains 10 and 15 because "call_user_func" called our functions for
us. This is possible because the string 'double' and the anonymous function
$triple are expressions. Note that we can even use this technique to call an
anonymous function without ever giving it a name:

<?php
$my_number 
call_user_func(function($x) { return $x; }, 5);
?>

$my_number is now 20, since "call_user_func" called the anonymous function,
which quadruples its argument, with the value 5.

Passing functions around as expressions like this is very useful whenever we
need to use a 'callback'. Great examples of this are array_map and array_reduce.
2013-07-12 14:06:48
http://php5.kiev.ua/manual/ru/language.expressions.html
Автор:
Regarding 12345alex at gmx dot net's example:

I think you miss the identical equal documentation line from: language.operators.comparison 

$a == $b     Equal     TRUE if $a is equal to $b after type juggling.
$a === $b     Identical     TRUE if $a is equal to $b, and they are of the same type. 

Try: 
print array() === NULL ? "True" : "False";

Check this:
var_dump(is_null(array()));
2017-01-12 17:10:42
http://php5.kiev.ua/manual/ru/language.expressions.html

    Поддержать сайт на родительском проекте КГБ