From db632ee03ca837fcdc4ca45e428ad7efb9c8135f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mario=20P=C3=A9rez?= Date: Sat, 31 Oct 2015 11:27:29 +0100 Subject: Create file for PHP translation es-ES --- es-es/php-es.html.markdown | 823 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 823 insertions(+) create mode 100644 es-es/php-es.html.markdown (limited to 'es-es/php-es.html.markdown') diff --git a/es-es/php-es.html.markdown b/es-es/php-es.html.markdown new file mode 100644 index 00000000..a8276e53 --- /dev/null +++ b/es-es/php-es.html.markdown @@ -0,0 +1,823 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Mario Pérez", "https://github.com/MarioPerezEsteso"] +lang: es-es +filename: learnphp-es.php +--- + +This document describes PHP 5+. + +```php + +Hello World Again! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (a leading 0 denotes an octal number) +$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) + +// Floats (aka doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Delete variable +unset($int1); + +// Arithmetic +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 + +// Shorthand arithmetic +$number = 0; +$number += 1; // Increment $number by 1 +echo $number++; // Prints 1 (increments after evaluation) +echo ++$number; // Prints 3 (increments before evaluation) +$number /= $float; // Divide and assign the quotient to $number + +// Strings should be enclosed in single quotes; +$sgl_quotes = '$String'; // => '$String' + +// Avoid using double quotes except to embed other variables +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Special characters are only escaped in double quotes +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// Enclose a variable in curly braces if needed +$money = "I have $${number} in the bank."; + +// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners +$nowdoc = <<<'END' +Multi line +string +END; + +// Heredocs will do string interpolation +$heredoc = << 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4 introduced a new syntax +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // prints 1 + +// List literals implicitly assign integer keys +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + +// Add an element to the end of an array +$array[] = 'Four'; +// or +array_push($array, 'Five'); + +// Remove element from array +unset($array[3]); + +/******************************** + * Output + */ + +echo('Hello World!'); +// Prints Hello World! to stdout. +// Stdout is the web page if running in a browser. + +print('Hello World!'); // The same as echo + +// echo and print are language constructs too, so you can drop the parentheses +echo 'Hello World!'; +print 'Hello World!'; + +$paragraph = 'paragraph'; + +echo 100; // Echo scalar variables directly +echo $paragraph; // or variables + +// If short open tags are configured, or your PHP version is +// 5.4.0 or greater, you can use the short echo syntax +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Dumps type and value of variable to stdout +var_dump($z); // prints int(0) + +// Prints variable to stdout in human-readable format +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) + +/******************************** + * Logic + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assert throws a warning if its argument is not true + +// These comparisons will always be true, even if the types aren't the same. +assert($a == $b); // equality +assert($c != $a); // inequality +assert($c <> $a); // alternative inequality +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// The following will only be true if the values match and are the same type. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// 'Spaceship' operator (since PHP 7) +// Returns 0 if values on either side are equal +// Returns 1 if value on the left is greater +// Returns -1 if the value on the right is greater + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 since they are equal +echo $a <=> $b; // -1 since $a < $b +echo $b <=> $a; // 1 since $b > $a + +// Variables can be converted between types, depending on their usage. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (strings are coerced to integers) + +$string = 'one'; +echo $string + $string; // => 0 +// Outputs 0 because the + operator cannot cast the string 'one' to a number + +// Type casting can be used to treat a variable as another type + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// There are also dedicated functions for casting most types +$integer = 5; +$string = strval($integer); + +$var = null; // Null value + + +/******************************** + * Control Structures + */ + +if (true) { + print 'I get printed'; +} + +if (false) { + print 'I don\'t'; +} else { + print 'I get printed'; +} + +if (false) { + print 'Does not get printed'; +} elseif(true) { + print 'Does'; +} + +// ternary operator +print (false ? 'Does not get printed' : 'Does'); + +// ternary shortcut operator since PHP 5.3 +// equivalent of "$x ? $x : 'Does'"" +$x = false; +print($x ?: 'Does'); + +// null coalesce operator since php 7 +$a = null; +$b = 'Does print'; +echo $a ?? 'a is not set'; // prints 'a is not set' +echo $b ?? 'b is not set'; // prints 'Does print' + + +$x = 0; +if ($x === '0') { + print 'Does not print'; +} elseif($x == '1') { + print 'Does not print'; +} else { + print 'Does print'; +} + + + +// This alternative syntax is useful for templates: +?> + + +This is displayed if the test is truthy. + +This is displayed otherwise. + + + 2, 'car' => 4]; + +// Foreach loops can iterate over arrays +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // Prints "24" + +echo "\n"; + +// You can iterate over the keys as well as the values +foreach ($wheels as $vehicle => $wheel_count) { + echo "A $vehicle has $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Exit out of the while loop + } + echo $i++; +} // Prints "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Skip this iteration of the loop + } + echo $i; +} // Prints "0124" + + +/******************************** + * Functions + */ + +// Define a function with "function": +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + +// A valid function name starts with a letter or underscore, followed by any +// number of letters, numbers, or underscores. + +function add ($x, $y = 1) { // $y is optional and defaults to 1 + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result is not accessible outside the function +// print $result; // Gives a warning. + +// Since PHP 5.3 you can declare anonymous functions; +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Functions can return functions +function bar ($x, $y) { + // Use 'use' to bring in outside variables + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Prints "A - B - C" + +// You can call named functions using strings +$function_name = 'add'; +echo $function_name(1, 2); // => 3 +// Useful for programatically determining which function to run. +// Or, use call_user_func(callable $callback [, $parameter [, ... ]]); + + +// You can get the all the parameters passed to a function +function parameters() { + $numargs = func_num_args(); + if ($numargs > 0) { + echo func_get_arg(0) . ' | '; + } + $args_array = func_get_args(); + foreach ($args_array as $key => $arg) { + echo $key . ' - ' . $arg . ' | '; + } +} + +parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | + +// Since PHP 5.6 you can get a variable number of arguments +function variable($word, ...$list) { + echo $word . " || "; + foreach ($list as $item) { + echo $item . ' | '; + } +} + +variable("Separate", "Hello", "World") // Separate || Hello | World | + +/******************************** + * Includes + */ + +instanceProp = $instanceProp; + } + + // Methods are declared as functions inside a class + public function myMethod() + { + print 'MyClass'; + } + + //final keyword would make a function unoverridable + final function youCannotOverrideMe() + { + } + +/* + * Declaring class properties or methods as static makes them accessible without + * needing an instantiation of the class. A property declared as static can not + * be accessed with an instantiated class object (though a static method can). + */ + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +// Class constants can always be accessed statically +echo MyClass::MY_CONST; // Outputs 'value'; + +echo MyClass::$staticVar; // Outputs 'static'; +MyClass::myStaticMethod(); // Outputs 'I am static'; + +// Instantiate classes using new +$my_class = new MyClass('An instance property'); +// The parentheses are optional if not passing in an argument. + +// Access class members using -> +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// Extend classes using "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// You can use "magic methods" to create getters and setters +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Will use the __get() method +$x->property = 'Something'; // Will use the __set() method + +// Classes can be abstract (using the abstract keyword) or +// implement interfaces (using the implements keyword). +// An interface is declared with the interface keyword. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Classes can implement more than one interface +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Traits + */ + +// Traits are available from PHP 5.4.0 and are declared using "trait" + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + + Date: Sat, 31 Oct 2015 15:32:24 +0100 Subject: Translate learn PHP to es-es --- es-es/php-es.html.markdown | 714 +++++++++++++++++++++++---------------------- 1 file changed, 358 insertions(+), 356 deletions(-) (limited to 'es-es/php-es.html.markdown') diff --git a/es-es/php-es.html.markdown b/es-es/php-es.html.markdown index a8276e53..fa52353c 100644 --- a/es-es/php-es.html.markdown +++ b/es-es/php-es.html.markdown @@ -9,121 +9,121 @@ lang: es-es filename: learnphp-es.php --- -This document describes PHP 5+. +Este documento explica el funcionamiento de PHP 5+. ```php - -Hello World Again! +¡Hola Mundo de nuevo! 12 $int2 = -12; // => -12 -$int3 = 012; // => 10 (a leading 0 denotes an octal number) -$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) +$int3 = 012; // => 10 (un 0 al comienzo declara un número octal) +$int4 = 0x0F; // => 15 (un 0x al comienzo declara un hexadecimal) -// Floats (aka doubles) +// Floats (también conocidos como doubles) $float = 1.234; $float = 1.2e3; $float = 7E-10; -// Delete variable +// Eliminar variable unset($int1); -// Arithmetic -$sum = 1 + 1; // 2 -$difference = 2 - 1; // 1 -$product = 2 * 2; // 4 -$quotient = 2 / 1; // 2 +// Operaciones aritméticas +$suma = 1 + 1; // 2 +$diferencia = 2 - 1; // 1 +$producto = 2 * 2; // 4 +$cociente = 2 / 1; // 2 -// Shorthand arithmetic -$number = 0; -$number += 1; // Increment $number by 1 -echo $number++; // Prints 1 (increments after evaluation) -echo ++$number; // Prints 3 (increments before evaluation) -$number /= $float; // Divide and assign the quotient to $number +// Operaciones aritméticas de escritura rápida +$numero = 0; +$numero += 1; // Incrementa $numero en 1 +echo $numero++; // Imprime 1 (incremento después la evaluación) +echo ++$numero; // Imprime 3 (incremento antes de la evaluación) +$numero /= $float; // Divide y asigna el cociente a $numero -// Strings should be enclosed in single quotes; +// Las cadenas de caracteres deben declararse entre comillas simples $sgl_quotes = '$String'; // => '$String' -// Avoid using double quotes except to embed other variables +// Evita utilizar comillas dobles excepto para embeber otras variables $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' -// Special characters are only escaped in double quotes -$escaped = "This contains a \t tab character."; -$unescaped = 'This just contains a slash and a t: \t'; +// Los caracteres especiales solo son válidos entre comillas dobles +$escaped = "Esto contiene \t un caracter tabulador."; +$unescaped = 'Esto solo contiene una barra y una t: \t'; -// Enclose a variable in curly braces if needed -$money = "I have $${number} in the bank."; +// Rodea una variable entre corchetes si es necesario +$dinero = "Tengo $${numero} en el banco."; -// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners +// Desde PHP 5.3, los nowdocs pueden ser utilizados para multilíneas no interpoladas $nowdoc = <<<'END' Multi line string END; -// Heredocs will do string interpolation +// Heredocs interpola cadenas de caracteres $heredoc = << 1, 'Two' => 2, 'Three' => 3); +// Funciona con todas las versiones de php +$asociativo = array('Uno' => 1, 'Dos' => 2, 'Tres' => 3); -// PHP 5.4 introduced a new syntax -$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; +// PHP 5.4 introdujo una nueva sintaxis +$asociativo = ['Uno' => 1, 'Dos' => 2, 'Tres' => 3]; -echo $associative['One']; // prints 1 +echo $asociativo['Uno']; // imprime 1 -// List literals implicitly assign integer keys -$array = ['One', 'Two', 'Three']; -echo $array[0]; // => "One" +// Lista literales implícitamente asignados con claves enteras +$array = ['Uno', 'Dos', 'Tres']; +echo $array[0]; // => "Uno" -// Add an element to the end of an array -$array[] = 'Four'; -// or -array_push($array, 'Five'); +// Añadir un elemento al final de un array +$array[] = 'Cuatro'; +// o +array_push($array, 'Cinco'); -// Remove element from array +// Eliminar un elemento de un array unset($array[3]); /******************************** - * Output + * Salidas por pantalla */ -echo('Hello World!'); -// Prints Hello World! to stdout. -// Stdout is the web page if running in a browser. +echo('¡Hola Mundo!'); +// Imprime ¡Hola Mundo! en stdout. +// Stdout es la página web si se está ejecutando en un navegador. -print('Hello World!'); // The same as echo +print('!Hola Mundo!'); // Es lo mismo que echo -// echo and print are language constructs too, so you can drop the parentheses -echo 'Hello World!'; -print 'Hello World!'; +// No es necesario el paréntesis en echo y print +echo '¡Hola Mundo!'; +print '¡Hola Mundo!'; -$paragraph = 'paragraph'; +$parrafo = 'parrafo'; -echo 100; // Echo scalar variables directly -echo $paragraph; // or variables +echo 100; // Haz echo de escalares directamente +echo $parrafo; // o de variables -// If short open tags are configured, or your PHP version is -// 5.4.0 or greater, you can use the short echo syntax +// Si las etiquetas cortas estás configuradas y tu versión de PHP es +// la 5.4.0 o superior, puede utilizar la sintaxis abreviada de echo ?> -

+

2 echo $z; // => 2 @@ -194,179 +194,178 @@ $y = 0; echo $x; // => 2 echo $z; // => 0 -// Dumps type and value of variable to stdout -var_dump($z); // prints int(0) +// Dump muestra el tipo y valor de una variable en stdout +var_dump($z); // imprime int(0) -// Prints variable to stdout in human-readable format -print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) +// Para mostrar el valor de una variable en un formato legible para humanos +print_r($array); // imprime: Array ( [0] => Uno [1] => Dos [2] => Tres ) /******************************** - * Logic + * Lógica */ $a = 0; $b = '0'; $c = '1'; $d = '1'; -// assert throws a warning if its argument is not true +// assert lanza una advertencia si su argumento no es verdadero -// These comparisons will always be true, even if the types aren't the same. -assert($a == $b); // equality -assert($c != $a); // inequality -assert($c <> $a); // alternative inequality +// Estas comparaciones siempre serán verdaderas, incluso si los tipos no son los mismos. +assert($a == $b); // igualdad +assert($c != $a); // desigualdad +assert($c <> $a); // desigualdad alternativa assert($a < $c); assert($c > $b); assert($a <= $b); assert($c >= $d); -// The following will only be true if the values match and are the same type. +// Los siguiente solo será verdadero si los valores coinciden y son del mismo tipo. assert($c === $d); assert($a !== $d); assert(1 === '1'); assert(1 !== '1'); -// 'Spaceship' operator (since PHP 7) -// Returns 0 if values on either side are equal -// Returns 1 if value on the left is greater -// Returns -1 if the value on the right is greater +// Operador 'Spaceship' (desde PHP 7) +// Devuelve 0 si ambos valores son iguales +// Devuelve 1 si el valor de la izquierda es mayor +// Devuelve -1 si el valor de la derecha es mayor $a = 100; $b = 1000; -echo $a <=> $a; // 0 since they are equal -echo $a <=> $b; // -1 since $a < $b -echo $b <=> $a; // 1 since $b > $a +echo $a <=> $a; // 0 porque son iguales +echo $a <=> $b; // -1 porque $a < $b +echo $b <=> $a; // 1 porque $b > $a -// Variables can be converted between types, depending on their usage. +// Las variables pueden ser convertidas entre tipos, dependiendo de su uso. -$integer = 1; -echo $integer + $integer; // => 2 +$entero = 1; +echo $entero + $entero; // => 2 $string = '1'; -echo $string + $string; // => 2 (strings are coerced to integers) +echo $string + $string; // => 2 (los strings son convertidos a enteros) -$string = 'one'; +$string = 'uno'; echo $string + $string; // => 0 -// Outputs 0 because the + operator cannot cast the string 'one' to a number +// Muestra un 0 porque el operador + no puede convertir la cadena de caracteres 'uno' a un número -// Type casting can be used to treat a variable as another type +// La conversión de tipos puede ser utilizada para tratar a una variable como otro tipo $boolean = (boolean) 1; // => true -$zero = 0; -$boolean = (boolean) $zero; // => false +$cero = 0; +$boolean = (boolean) $cero; // => false -// There are also dedicated functions for casting most types -$integer = 5; -$string = strval($integer); +// También hay funciones dedicadas a la conversión de tipos +$entero = 5; +$string = strval($entero); -$var = null; // Null value +$var = null; // Valor nulo /******************************** - * Control Structures + * Estructuras de control */ if (true) { - print 'I get printed'; + print 'He sido imprimido'; } if (false) { - print 'I don\'t'; + print 'Yo no'; } else { - print 'I get printed'; + print 'He sido imprimido'; } if (false) { - print 'Does not get printed'; + print 'No se imprime'; } elseif(true) { - print 'Does'; + print 'Sí se imprime'; } -// ternary operator -print (false ? 'Does not get printed' : 'Does'); +// operador ternario +print (false ? 'No se imprime' : 'Sí se imprime'); -// ternary shortcut operator since PHP 5.3 -// equivalent of "$x ? $x : 'Does'"" +// atajo para el operador ternario desde PHP 5.3 +// equivalente de "$x ? $x : 'Sí'"" $x = false; -print($x ?: 'Does'); +print($x ?: 'Sí'); -// null coalesce operator since php 7 +// operador 'no definido' desde php 7 $a = null; -$b = 'Does print'; -echo $a ?? 'a is not set'; // prints 'a is not set' -echo $b ?? 'b is not set'; // prints 'Does print' +$b = 'Imprime'; +echo $a ?? 'a no está definido'; // imprime 'a no está definido' +echo $b ?? 'b no está definido'; // imprime 'Imprime' $x = 0; if ($x === '0') { - print 'Does not print'; + print 'No imprime'; } elseif($x == '1') { - print 'Does not print'; + print 'No imprime'; } else { - print 'Does print'; + print 'Imprime'; } -// This alternative syntax is useful for templates: +// Esta sintaxis alternativa se utiliza para plantillas: ?> -This is displayed if the test is truthy. +Esto se muestra si la evaluación es verdadera. -This is displayed otherwise. +En otro caso, se muestra esto. 2, 'car' => 4]; +$ruedas = ['bicicleta' => 2, 'coche' => 4]; -// Foreach loops can iterate over arrays -foreach ($wheels as $wheel_count) { - echo $wheel_count; -} // Prints "24" +// Los bucles foreach pueden iterar por arrays +foreach ($ruedas as $numero_ruedas) { + echo $numero_ruedas; +} // Imprime "24" echo "\n"; -// You can iterate over the keys as well as the values -foreach ($wheels as $vehicle => $wheel_count) { - echo "A $vehicle has $wheel_count wheels"; +// También se puede iterar sobre las claves, así como sobre los valores +foreach ($ruedas as $vehiculo => $numero_ruedas) { + echo "Un $vehiculo tiene $numero_ruedas ruedas"; } echo "\n"; @@ -374,45 +373,45 @@ echo "\n"; $i = 0; while ($i < 5) { if ($i === 3) { - break; // Exit out of the while loop + break; // Sale fuera del bucle while } echo $i++; -} // Prints "012" +} // Imprime "012" for ($i = 0; $i < 5; $i++) { if ($i === 3) { - continue; // Skip this iteration of the loop + continue; // Se salta esta iteración del bucle } echo $i; -} // Prints "0124" +} // Imprime "0124" /******************************** - * Functions + * Funciones */ -// Define a function with "function": -function my_function () { - return 'Hello'; +// Define una función con "function": +function mi_funcion () { + return 'Hola'; } -echo my_function(); // => "Hello" +echo mi_funcion(); // => "Hola" -// A valid function name starts with a letter or underscore, followed by any -// number of letters, numbers, or underscores. +// Un nombre válido de función comienza con una letra o guión bajo, seguido de cualquier +// número de letras, números o guiones bajos. -function add ($x, $y = 1) { // $y is optional and defaults to 1 - $result = $x + $y; - return $result; +function anadir ($x, $y = 1) { // $y es opcional y por defecto es 1 + $resultado = $x + $y; + return $resultado; } -echo add(4); // => 5 -echo add(4, 2); // => 6 +echo anadir(4); // => 5 +echo anadir(4, 2); // => 6 -// $result is not accessible outside the function -// print $result; // Gives a warning. +// $resultado no es accesible fuera de la función +// print $resultado; // Devuelve una advertencia. -// Since PHP 5.3 you can declare anonymous functions; +// Desde PHP 5.3 se pueden declarar funciones anónimas $inc = function ($x) { return $x + 1; }; @@ -423,28 +422,28 @@ function foo ($x, $y, $z) { echo "$x - $y - $z"; } -// Functions can return functions +// Las funciones pueden devolver funciones function bar ($x, $y) { - // Use 'use' to bring in outside variables + // Utiliza 'use' para meter variables de fuera de la función return function ($z) use ($x, $y) { foo($x, $y, $z); }; } $bar = bar('A', 'B'); -$bar('C'); // Prints "A - B - C" +$bar('C'); // Imprime "A - B - C" -// You can call named functions using strings -$function_name = 'add'; -echo $function_name(1, 2); // => 3 -// Useful for programatically determining which function to run. -// Or, use call_user_func(callable $callback [, $parameter [, ... ]]); +// Puedes llamar a funciones utilizando cadenas de caracteres +$nombre_funcion = 'add'; +echo $nombre_funcion(1, 2); // => 3 +// Es útil para determinarl qué función ejecutar. +// O, utiliza call_user_func(callable $callback [, $parameter [, ... ]]); -// You can get the all the parameters passed to a function -function parameters() { - $numargs = func_num_args(); - if ($numargs > 0) { +// Puedes obtener todos los parámetros pasados a una función +function parametros() { + $numero_argumentos = func_num_args(); + if ($numero_argumentos > 0) { echo func_get_arg(0) . ' | '; } $args_array = func_get_args(); @@ -453,151 +452,153 @@ function parameters() { } } -parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | +parametros('Hola', 'Mundo'); // Hola | 0 - Hola | 1 - Mundo | -// Since PHP 5.6 you can get a variable number of arguments -function variable($word, ...$list) { - echo $word . " || "; - foreach ($list as $item) { +// Desde PHP 5.6 se puede obtener un número variable de argumentos +function variable($palabra, ...$lista) { + echo $palabra . " || "; + foreach ($lista as $item) { echo $item . ' | '; } } -variable("Separate", "Hello", "World") // Separate || Hello | World | +variable("Separa", "Hola", "Mundo") // Separa || Hola | Mundo | /******************************** * Includes */ instanceProp = $instanceProp; } - // Methods are declared as functions inside a class - public function myMethod() + // Los métodos son declarados como funciones dentro de una clase + public function miMetodo() { - print 'MyClass'; + print 'MiClase'; } - //final keyword would make a function unoverridable - final function youCannotOverrideMe() + // la palabra clave final hará una función no sobreescribible + final function noMePuedesSobreEscribir() { } /* - * Declaring class properties or methods as static makes them accessible without - * needing an instantiation of the class. A property declared as static can not - * be accessed with an instantiated class object (though a static method can). + * Declarar propiedades de clase o métodos como estáticos los hace accesibles sin + * necesidad de instanciar la clase. Una propiedad declarada como estática no + * puede ser accedida mediante una instancia de la clase, pero sí mediante un + * método estático. */ - public static function myStaticMethod() + public static function miMetodoEstatico() { - print 'I am static'; + print 'Soy estático'; } } -// Class constants can always be accessed statically -echo MyClass::MY_CONST; // Outputs 'value'; +// Las constantes de una clase siempre pueden ser accedidas estáticamente +echo MiClase::MI_CONSTANTE; // Muestra 'valor'; -echo MyClass::$staticVar; // Outputs 'static'; -MyClass::myStaticMethod(); // Outputs 'I am static'; +echo MiClase::$staticVar; // Muestra 'static'; +MiClase::miMetodoEstatico(); // Muestra 'Soy estático'; -// Instantiate classes using new -$my_class = new MyClass('An instance property'); -// The parentheses are optional if not passing in an argument. +// Instancia una clase usando new +$mi_clase = new MiClase('Una instancia'); +// Los paréntesis son opcionales si no se pasa ningún argumento. -// Access class members using -> -echo $my_class->property; // => "public" -echo $my_class->instanceProp; // => "An instance property" -$my_class->myMethod(); // => "MyClass" +// Accede a los miembros de una clase utilizando -> +echo $mi_clase->propiedad; // => "public" +echo $mi_clase->instanceProp; // => "Una instancia" +$mi_clase->miMetodo(); // => "MiClase" -// Extend classes using "extends" -class MyOtherClass extends MyClass +// Extender clases utilizando "extends" +class MiOtraClase extends MiClase { - function printProtectedProperty() + function imprimePropiedadProtegida() { echo $this->prot; } - // Override a method - function myMethod() + // Sobreescribe un método + function miMetodo() { - parent::myMethod(); - print ' > MyOtherClass'; + parent::miMetodo(); + print ' > MiOtraClase'; } } -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Prints "protected" -$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" +$mi_otra_clase = new MiOtraClase('Propiedad de instancia'); +$mi_otra_clase->imprimePropiedadProtegida(); // => Imprime "protected" +$mi_otra_clase->miMetodo(); // Imprime "MiClase > MiOtraClase" -final class YouCannotExtendMe +final class NoMePuedesExtender { } -// You can use "magic methods" to create getters and setters -class MyMapClass +// Puedes utilizar "métodos mágicos" para crear los getters y setters +class MiClaseMapeada { - private $property; + private $propiedad; public function __get($key) { @@ -610,60 +611,60 @@ class MyMapClass } } -$x = new MyMapClass(); -echo $x->property; // Will use the __get() method -$x->property = 'Something'; // Will use the __set() method +$x = new MiClaseMapeada(); +echo $x->propiedad; // Utilizará el método __get() +$x->propiedad = 'Algo'; // Utilizará el método __set() -// Classes can be abstract (using the abstract keyword) or -// implement interfaces (using the implements keyword). -// An interface is declared with the interface keyword. +// Las clases pueden ser abstractas (utilizando la palabra clave abstract) o +// implementando interfaces (utilizando la palabra clave implements). +// Una interfaz puede ser declarada con la palabra clave interface. -interface InterfaceOne +interface InterfazUno { - public function doSomething(); + public function hazAlgo(); } -interface InterfaceTwo +interface InterfazDos { - public function doSomethingElse(); + public function hazOtraCosa(); } -// interfaces can be extended -interface InterfaceThree extends InterfaceTwo +// las interfaces pueden ser extendidas +interface InterfazTres extends InterfazDos { - public function doAnotherContract(); + public function hazCualquierOtraCosa(); } -abstract class MyAbstractClass implements InterfaceOne +abstract class MiClaseAbstracta implements InterfazUno { - public $x = 'doSomething'; + public $x = 'hazAlgo'; } -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +class MiOtraClase extends MiClaseAbstracta implements InterfazDos { - public function doSomething() + public function hazAlgo() { echo $x; } - public function doSomethingElse() + public function hazOtraCosa() { - echo 'doSomethingElse'; + echo 'hazOtraCosa'; } } -// Classes can implement more than one interface -class SomeOtherClass implements InterfaceOne, InterfaceTwo +// Las clases pueden implementar más de una interfaz +class CualquierOtraClase implements InterfazUno, InterfazDos { - public function doSomething() + public function hazAlgo() { - echo 'doSomething'; + echo 'hazAlgo'; } - public function doSomethingElse() + public function hazOtraCosa() { - echo 'doSomethingElse'; + echo 'hazOtraCosa'; } } @@ -672,65 +673,65 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo * Traits */ -// Traits are available from PHP 5.4.0 and are declared using "trait" +// Los traits están disponibles desde PHP 5.4.0 y son declarados utilizando "trait" -trait MyTrait +trait MiTrait { - public function myTraitMethod() + public function miMetodoTrait() { - print 'I have MyTrait'; + print 'Tengo trait'; } } -class MyTraitfulClass +class MiClaseTrait { - use MyTrait; + use MiTrait; } -$cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$cls = new MiClaseTrait(); +$cls->miMetodoTrait(); // Imprime "Tengo trait" /******************************** * Namespaces */ -// This section is separate, because a namespace declaration -// must be the first statement in a file. Let's pretend that is not the case +// Esta sección está separada porque una declaración de namespace debe +// ser la primera sentencia en un archivo. Vamos a suponer que no es el caso