|
|
 |
CapÃtulo 15. Operadores
Un operador es algo a lo que usted entrega uno o más valores
(o expresiones, en jerga de programación) y produce otro
valor (de modo que la construcción misma se convierte en una
expresión). Asà que puede pensar sobre las funciones
o construcciones que devuelven un valor (como print) como
operadores, y en aquellas que no devuelven nada (como echo) como
cualquier otra cosa.
Existen tres tipos de operadores. En primer lugar se encuentra el
operador unario, el cual opera sobre un único valor, por
ejemplo ! (el operador de negación) o ++ (el operador de
incremento). El segundo grupo se conoce como operadores binarios;
éste grupo contiene la mayorÃa de operadores que
soporta PHP, y una lista se encuentra disponible más
adelante en la sección Precedencia de
Operadores.
El tercer grupo consiste del operador ternario: ?:. Éste
debe ser usado para seleccionar entre dos expresiones, en base a
una tercera, en lugar de seleccionar dos sentencias o rutas de
ejecución. Rodear las expresiones ternarias con
paréntesis es una muy buena idea.
La precedencia de un operador indica qué tan "cerca" se
agrupan dos expresiones. Por ejemplo, en la expresión
1 + 5 * 3, la respuesta es
16 y no 18, ya que el
operador de multiplicación ("*") tiene una mayor
precedencia que el operador de adición ("+"). Los
paréntesis pueden ser usados para marcar la precedencia, si
resulta necesario. Por ejemplo: (1 + 5) * 3
evalúa a 18. Si la precedencia de los
operadores es la misma, se utiliza una asociación de
izquierda a derecha.
La siguiente tabla lista la precedencia de los operadores, con
aquellos de mayor precedencia listados al comienzo de la
tabla. Los operadores en la misma lÃnea tienen la misma
precedencia, en cuyo caso su asociatividad decide el orden para
evaluarlos.
Tabla 15-1. Precedencia de Operadores
La asociatividad de izquierda quiere decir que la expresión
es evaluada desde la izquierda a la derecha, la asociatividad de
derecha quiere decir lo contrario.
Ejemplo 15-1. Asociatividad |
<?php
$a = 3 * 3 % 5; $a = true ? 0 : true ? 1 : 2; $a = 1;
$b = 2;
$a = $b += 3; ?>
|
|
Use paréntesis para incrementar la legibilidad del
código.
Nota:
Aunque ! tiene una mayor precedencia
que =, PHP permitirá aun expresionas
similares a la siguiente: if (!$a = foo()), en
cuyo caso la salida de foo() va a dar
a $a.
T Chan
19-Aug-2006 10:30
In response to 26-Mar-2001 08:53, parens don't need to have precedence. There's only one way to convert them to a syntax tree. I can't think of a sensible reason it could be ambiguous either (and sensible language designers will make ( always pair with ) so there can't be any ambiguity).
In response to 12-Aug-2005 08:47, you can do <?php $myvar OR ($myvar = 1); ?>, or the equivalent <?php !$myvar AND $myvar = 1; ?>, and if you have to use ifs, <?php if(!$myvar) { $myvar = 1; } ?> will do just fine (though in general, I'd be careful using boolean expressions as an indicator of success/failure when 0 could be a valid value. And you probably want to use isset($myvariable)).
In response to the manual, associativity doesn't determine the order of evaluation - it determines how it's "bracketed": a=b=c=1 is equivalent to a=(b=(c=1)), but a is evaluated first (an important point if evaluating a has side-effects)
<?php
function one($str) {
echo "$str";
return 1;
}
$a = array(1,2);
$a[one("A")] = $a[one("B")] = 1; ?>
golotyuk at gmail dot com
09-Jul-2006 09:51
Simple POST and PRE incremnt sample:
<?php
$b = 5;
$a = ( ( ++$b ) > 5 ); echo (int)$a;
$b = 5;
$a = ( ( $b++ ) > 5 ); echo (int)$a;
?>
This will output 10, because of the difference in post- and pre-increment operations
dlyons at lyons42 dot com
26-Nov-2005 03:30
Re: Rick on 2-Sep-2005.
Actually, the C equivalent of "$a[$c++]=$b[$c++];" has undefined behavior, and the increments are by no means guaranteed to happen after the assignment in C. (Search for a discussion of C "sequence points" for details.)
sm
02-Sep-2005 05:15
Note the highly unfortunate difference from Java, which associates the trinary operator right-to-left.
---------------------------- source
function trinaryTest($foo){ // works as you think in Java, but not PHP
$bar = $foo > 20
? "greater than 20"
: $foo > 10
? "greater than 10"
: $foo > 5
? "greater than 5"
: "not worthy of consideration";
echo $foo." => ".$bar."\n";
}
echo "\n\n\n----trinaryTest\n\n";
trinaryTest(21);
trinaryTest(11);
trinaryTest(6);
trinaryTest(4);
function trinaryTestParens($foo){
$bar = $foo > 20
? "greater than 20"
: ($foo > 10
? "greater than 10"
: ($foo > 5
? "greater than 5"
: "not worthy of consideration"));
echo $foo." => ".$bar."\n";
}
echo "\n\n\n----trinaryTestParens\n\n";
trinaryTestParens(21);
trinaryTestParens(11);
trinaryTest(6);
trinaryTestParens(4);
---------------------------- output
----trinaryTest
21 => greater than 5
11 => greater than 5
6 => greater than 5
4 => not worthy of consideration
----trinaryTestParens
21 => greater than 20
11 => greater than 10
6 => greater than 5
4 => not worthy of consideration
rick at nomorespam dot fourfront dot ltd dot uk
02-Sep-2005 03:51
A quick note to any C developers out there, assignment expressions are not interpreted as you may expect - take the following code ;-
<?php
$a=array(1,2,3);
$b=array(4,5,6);
$c=1;
$a[$c++]=$b[$c++];
print_r( $a ) ;
?>
This will output;-
Array ( [0] => 1 [1] => 6 [2] => 3 )
as if the code said;-
$a[1]=$b[2];
Under a C compiler the result is;-
Array ( [0] => 1 [1] => 5 [2] => 3 )
as if the code said;-
$a[1]=$b[1];
It would appear that in php the increment in the left side of the assignment is processed prior to processing the right side of the assignment, whereas in C, neither increment occurs until after the assignment.
kit dot lester at lycos dot co dot uk
22-Aug-2005 05:38
D'oh! please ignore (& forgive) the first paragraph in my note yesterday - I said that a diadic operator had the same precedence & associativity as a bunch of monadics. A bit of early senility must have struck me.
When I find time I'll rework my test to find out what I should have said - but using instanceof monadically didn't cause any visible errors in the test, so it could take a while.
[I'd be delighted if someone else beats me to it/ spares me the difficulties of seeing what's wrong in something that shouldn't have worked.]
kit dot lester at lycos do co dot uk
21-Aug-2005 09:21
Table 15-1 omits the precedence of instanceof - testing suggests it to be of the same precedence as not, negate, casting, and @.
The table also omits the precedence (and associativity) of the "execution operator" - but since that's a sort of quoting, I don't think it meaningfully has a precedence or associativity - they explain what is to happen where there's an open-endedness in the sense of missing brackets, and the quoting is a sort of bracket. (At least: because of the execution operator's double-ended closedness, I can't figure out any code where it would matter, so I can't test it.)
webmaster AT cafe-clope DOT net
12-Aug-2005 12:47
I regularly use some syntax like :
<?php
if(!$myvar)
$myvar = $value ;
?>
and
<?php
if($myvar)
echo "myvar is $myvar today" ;
?>
(or <?php echo ($myvar ? "myvar is $myvar today" : "") ?>)
It's small, but can become heavy when used too much.
Isn't there some trick to better such syntaxes ?
I was wondering about using things like :
<?php $myvar ||= $value ; ?>
<?php $myvar ?= $value ; ?>
<?php echo ($myvar ? "myvar is $myvar today") ; ?>
edwardsbc at yahoo dot com
04-May-2005 10:26
In response to npeelman at cfl dot rr dot com
29-Dec-2004 06:22:
You have misunderstood the behaviour of the interpreter.
With out the curly braces and the single quoted key identifier, the interpreter "assumes" you meant your CONSTANT to be a string. This ONLY works within a parsed (double quoted) string. And it doesn't help you at all if your array is multi-dimensional. I consider this a very bad habbit because it will get you in trouble elsewhere. Try the following:
<?php
define('item','AnyOldThing');
define('b',12);
$arr['item']['b'] = 'string';
$arr['AnyOldThing'][12]= 'Maybe not what I intended.';
echo "This is a {$arr['item']['b']}"; echo "This is a $arr[item][b]"; echo $arr[item][b]; ?>
npeelman at cfl dot rr dot com
29-Dec-2004 03:22
Update to message by yasuo_ohgaki at hotmail dot com:
I know this is an old message but when using an Associative array in a string you do not have to use { and } to resolve ambiguity.
ex:
Associative Array in string:
$arr['item'] = 'string';
echo "This is {$arr['item']}"; //prints "This is string".
...does work but, so does:
echo "This is $arr[item]"; //prints "This is string".
... simply enclose the whole string with double quotes and leave out the single quotes from around the index name. This simplifies the code and makes things easier to read.
Stopping at the dot completely
01-Sep-2004 01:33
The low precedence of the OR operator is useful for error control statements such as this one:
$my_file = @file ('non_existent_file') or die ("Failed opening file: error was '$php_errormsg'");
Notice the good readability of the code.
22-Aug-2004 09:51
I think warhog's note about the differing precedence between && / AND and || / OR is worth repeating. Since && and || evaluate before the assignment operator (=) while AND and OR evaluate after it, you can get COMPLETELY different results if you don't fully parenthesise.
I cannot imagine when it would ever be important that those two pairs have differing precedence, but they do. And I just spent two hours discovering that the hard way because I broke my career-long rule:
*Always fully parenthesise!*
11-Jun-2004 07:22
Warhog wrote: "maybe usefull for some tricky coding and helpfull to prevent bugs :D"
I'm sure Warhog was being facetious, but for the new programmers in the audience I'd like to point out that 'tricky coding' and relying on precedence/order of evaluation are both well-known ways to *produce* bugs.
Use parentheses instead.
09-Jun-2004 05:58
of course this should be clear, but i think it has to be mentioned espacially:
AND is not the same like &&
for example:
<?php $a && $b || $c; ?>
is not the same like
<?php $a AND $b || $c; ?>
the first thing is
(a and b) or c
the second
a and (b or c)
'cause || has got a higher priority than and, but less than &&
of course, using always [ && and || ] or [ AND and OR ] would be okay, but than you should at least respect the following:
<?php $a = $b && $c; ?>
<?php $a = $b AND $c; ?>
the first code will set $a to the result of the comparison $b with $c, both have to be true, while the second code line will set $a like $b and THAN - after that - compare the success of this with the value of $c
maybe usefull for some tricky coding and helpfull to prevent bugs :D
greetz, Warhog
yasuo_ohgaki at hotmail dot com
26-Mar-2001 12:34
About "{" and "}".
Sometimes PHP programmers need to use "{" and "}" to resolve ambiguity. Here is some examples.
Variable Variables:
$foo = "test";
$$bar = "this is";
echo "${$bar} $foo"; // prints "this is test"
Note: it is the same as
echo "$test $foo";
Array in string:
$arr[10][10][10] = "string";
echo "This is {$arr[10][10][10]}"; // prints "This is string"
Associative Array in string:
$arr['item'] = 'string';
echo "This is {$arr['item']}"; //prints "This is string".
yasuo_ohgaki at hotmail dot com
25-Mar-2001 11:53
Other Language books' operator precedence section usually include "(" and ")" - with exception of a Perl book that I have. (In PHP "{" and "}" should also be considered also). However, PHP Manual is not listed "(" and ")" in precedence list. It looks like "(" and ")" has higher precedence as it should be.
Note: If you write following code, you would need "()" to get expected value.
$bar = true;
$str = "TEST". ($bar ? 'true' : 'false') ."TEST";
Without "(" and ")" you will get only "true" in $str.
(PHP4.0.4pl1/Apache DSO/Linux, PHP4.0.5RC1/Apache DSO/W2K Server)
It's due to precedence, probably.
| |
|
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|