# data[].attributes.attachment_link.title
R (lenguaje de programación) - Wikipedia, la enciclopedia libre

# data[].attributes.attachment_link.description
R es una implementación de software libre del lenguaje S pero con soporte de alcance estático. Se trata de uno de los lenguajes más utilizados en investigación por la comunidad estadística, siendo además muy popular en el campo de la minería de datos, la investigación biomédica, la bioinformática y las matemáticas financieras.

# data[].attributes.attachment_link.readable_text
Go

Desarrollador(es)

Google
https://golang.org y https://go.dev

Información general

Extensiones comunes

.go

Paradigma

compilado concurrente, imperativo, estructurado ​​​

Apareció en

2009

Diseñado por

Robert Griesemer, Rob Pike y Ken Thompson

Última versión estable

1.16.5 ​ (03 de junio de 2021 (2 meses y 3 días))

Sistema de tipos

fuerte, estático

Implementaciones

gc (8g, 6g, 5g), gccgo

Influido por

C, Modula-2, Pascal, Oberon, Limbo

Sistema operativo

GNU/Linux, Mac OS X, Windows, otros​​

Licencia

BSD​ + patent grant​

Go es un lenguaje de programación concurrente y compilado inspirado en la sintaxis de C, que intenta ser dinámico como Python y con el rendimiento de C o C++. Ha sido desarrollado por Google​ y sus diseñadores iniciales fueron Robert Griesemer, Rob Pike y Ken Thompson. ​ Actualmente está disponible en formato binario para los sistemas operativos Windows, GNU/Linux, FreeBSD y Mac OS X, pudiendo también ser instalado en estos y en otros sistemas mediante el código fuente.​​ Go es un lenguaje de programación compilado, concurrente, imperativo, estructurado, orientado a objetos y con recolector de basura que de momento es soportado en diferentes tipos de sistemas UNIX, incluidos Linux, FreeBSD, Mac OS X y Plan 9 (puesto que parte del compilador está basado en un trabajo previo sobre el sistema operativo Inferno). Las arquitecturas soportadas son i386, amd64 y ARM.

El día de la publicación del lenguaje Go, Francis McCabe, desarrollador del lenguaje de programación Go! (anteriormente llamado Go), solicitó que se le cambiase el nombre al lenguaje de Google para evitar confusiones con su lenguaje.​ McCabe creó Go! en el año 2003; sin embargo, aún no ha registrado el nombre.​ Go es un nuevo lenguaje de programación para sistemas lanzado por Google en noviembre de 2009. Aunque empezó a ser desarrollado en septiembre de 2007 por Robert Griesemer, Rob Pike y Ken Thompson.

Características

Go es un proyecto opensource.​

Go usa una sintaxis similar a C.​

Go usa tipado estático (statically typed ).

Go es un lenguaje compilado, al igual que C y C++.

Provee de un recolector de basura , reflexión y algunas otras capacidades de lenguajes de alto nivel.

El binario de Go tiene la característica de compilación cruzada de manera nativa.

Go admite el paradigma de programación orientada a objetos, pero a diferencia de otros lenguajes de programación no dispone de herencia de tipos y tampoco de palabras clave que denoten claramente que soporta este paradigma.

En Go, la definición de un tipo ("clase") se realiza por medio de declaraciones separadas (interfaces, structs, embedded values).

Go permite el uso de delegación (a través de embedded values) y polimorfismo (por medio de interfaces).

Go utiliza la concurrencia a través de las gorutinas.

Go esta orientado a aprovechar sistemas con múltiples procesadores y procesamiento en red.​

Go admite la tipificación dinámica de datos también conocida como duck Typing.​​

Un struct puede implementar una interfaz de forma automática.​

Go no utiliza excepciones.​ Los creadores del lenguaje han dado varios motivos para que esto sea así. La principal es que añadir una capa de excepciones agrega una complejidad innecesaria al lenguaje y al entorno de ejecución. Por definición las excepciones deberían ser excepcionales pero al final se acaban usando como controladores del flujo de la aplicación y dejan de tener la finalidad de excepcionalidad. Según los creadores, las excepciones tienen que ser realmente excepcionales y el uso que se le da mayoritariamente no justifica su existencia.

Aunque su sintaxis es similar, Go difiere mucho de C. Véanse algunos ejemplos.

Declaraciones al revés

En Go las declaraciones se realizan al revés desde la perspectiva de C (o C++ o Java). La idea principal en C es que se declara una variable como una expresión que denota su tipo. Según los creadores, aunque la idea detrás de la declaración de tipos en C es buena, los tipos y las expresiones gramaticales no se mezclan demasiado bien y el resultado puede ser confuso. Go sin embargo, separa la expresión y la sintaxis de tipo, lo cual simplifica las cosas.

Punto y coma

En Go el uso del carácter punto y coma ";" al final de una instrucción es opcional.

Aritmética de punteros

Go no tiene aritmética de punteros. Según los creadores, la razón es la seguridad. Sin aritmética de punteros es posible crear un lenguaje en el que no se puede obtener una dirección ilegal que sea usada de forma incorrecta. La falta de aritmética de punteros simplifica la implementación del recolector de basura. Además, optimizando el compilador y con el hardware actual, un bucle que utiliza los índices de un array puede ser tan eficaz como un bucle que utiliza aritmética de punteros.

En Go, el uso de ++ y -- para incrementar y decrementar el valor de una variable es una sentencia y no una expresión. Además, solo puede utilizarse en su versión sufija pues según los autores, la versión prefija pierde todo su sentido en la ausencia de aritmética de punteros.

Programación orientada a objetos

Para algunos autores, la herencia o las clases no son conceptos esenciales para el paradigma de POO, sino más bien un medio de implementación. Existen desde hace tiempo lenguajes orientados a objetos que no admiten clases, sino que se basan en prototipos, como Javascript o . Según declaraciones de Alan Kay, creador de Smalltalk, lo esencial del paradigma es el paso de mensajes.​

Go tiene tipos y métodos, y permite un estilo de programación orientado a objetos que reemplaza el uso de clases por estructuras las cuales admiten construir jerarquías, es decir, no soporta el uso herencia y favorece en su lugar el patrón de composición. En Go, el concepto de "interfaz" es similar al usado en : cualquier objeto ( value) que cumpla el contrato especificado por una interfaz (sin necesidad de una declaración explícita) obtiene ese tipo. También existen formas de embeber estructuras dentro de otras estructuras para obtener algo análogo a las subclases. Los métodos de Go son más generales que los de C++ o Java, y se incluyen en las estructuras declarando funciones asociadas a estas. Pueden ser definidos para cualquier tipo de datos; no solo para los registros. Por su parte las interfaces de Go a diferencia de lenguajes como Java, son de tipo implícito, es decir que se considera que la interfaz ha sido implementada cuando una estructura implementa sus métodos aun cuando esto no se especifique.

El clásico programa Hola mundo en Go es similar a como se haría en C++. Con este típico ejemplo podemos apreciar que en cuanto a sintaxis son muy similares:

La notación de los comentarios es exactamente la misma que la de C++

Un programa para una aplicación web.

# data[].attributes.attachment_link.title
Go (lenguaje de programación) - Wikipedia, la enciclopedia libre

# data[].attributes.attachment_link.description
Go Desarrollador(es) Google https://golang.org y https://go.dev Información general Extensiones comunes .go Paradigma compilado concurrente, imperativo, estructurado ​​​ Apareció en 2009 Diseñado por Robert Griesemer, Rob Pike y Ken Thompson Última versión estable 1.16.5 ​ (03 de junio de 2021 (2 meses y 3 días)) Sistema de tipos fuerte, estático Implementaciones

# data[].attributes.attachment_link.title
¿Que es Go? ¿Para que sirve Golang? - El lenguaje creado por Google - Víctor Robles

# data[].attributes.attachment_link.readable_text
Por favor, En este artículo se detectaron varios problemas. edítalo para mejorarlo:

Este aviso fue puesto el 4 de mayo de 2019.

C

Desarrollador(es)

Dennis Ritchie y Laboratorios Bell

Información general

Extensiones comunes

.c, .h

Paradigma

Imperativo ( procedural), estructurado

Apareció en

1972

Diseñado por

Dennis Ritchie

Última versión estable

C18 (junio de 2018)

Última versión en pruebas

C2x

Sistema de tipos

Débil, estático

Implementaciones

GCC, Intel C, entre muchas más.

Dialectos

Cyclone, Unified Parallel C, Split-C, Cilk, C*

Influido por

B ( BCPL, CPL), ALGOL 68,[1] ​:201-208
Ensamblador, PL/I, Fortran

Ha influido a

Vala, C#, Objective-C, C++, AWK, bc, Java, JavaScript, PHP, Perl, NXC, D, Go, Rust, Python

Sistema operativo

Multiplataforma

C es un lenguaje de programación de propósito general​ originalmente desarrollado por Dennis Ritchie entre 1969 y 1972 en los Laboratorios Bell,​ como evolución del anterior lenguaje B, a su vez basado en BCPL.​​​

Al igual que B, es un lenguaje orientado a la implementación de sistemas operativos, concretamente Unix. C es apreciado por la eficiencia del código que produce y es el lenguaje de programación más popular para crear softwares de sistemas y aplicaciones.

Se trata de un lenguaje de tipos de datos estáticos, débilmente tipado, de medio nivel, que dispone de las estructuras típicas de los lenguajes de alto nivel pero, a su vez, dispone de construcciones del lenguaje que permiten un control a bajo nivel. Los compiladores suelen ofrecer extensiones al lenguaje que posibilitan mezclar código en ensamblador con código C o acceder directamente a memoria o dispositivos periféricos.

La primera estandarización del lenguaje C fue en ANSI, con el estándar X3.159-1989. El lenguaje que define este estándar fue conocido vulgarmente como ANSI C. Posteriormente, en 1990, fue ratificado como estándar ISO (ISO/IEC 9899:1990). La adopción de este estándar es muy amplia por lo que, si los programas creados lo siguen, el código es portable entre plataformas y/o arquitecturas.

Uno de los objetivos de diseño del lenguaje C es que solo sean necesarias unas pocas instrucciones en lenguaje máquina para traducir cada elemento del lenguaje, sin que haga falta un soporte intenso en tiempo de ejecución. Es muy posible escribir C a bajo nivel de abstracción; de hecho, C se usó como intermediario entre diferentes lenguajes.

En parte, a causa de ser de relativamente bajo nivel y de tener un modesto conjunto de características, se pueden desarrollar compiladores de C fácilmente. En consecuencia, el lenguaje C está disponible en un amplio abanico de plataformas (más que cualquier otro lenguaje). Además, a pesar de su naturaleza de bajo nivel, el lenguaje se desarrolló para incentivar la programación independiente de la máquina. Un programa escrito cumpliendo los estándares e intentando que sea portátil puede compilarse en muchos computadores.

C se desarrolló originalmente (conjuntamente con el sistema operativo Unix, con el que ha estado asociado mucho tiempo) por programadores para programadores. Sin embargo, ha alcanzado una popularidad enorme, y se ha usado en contextos muy alejados de la programación de software de sistema, para la que se diseñó originalmente.

Núcleo del lenguaje simple, con funcionalidades añadidas importantes, como funciones matemáticas y de gestión de archivos, proporcionadas por bibliotecas.

Es un lenguaje estructurado, i.e. tiene estructuras de control y tipos de datos estructurados definidos por el programador a partir de los tipos atómicos típicos y mediante arreglos, estructuras, uniones y punteros, incluidos los que apuntan a una función.

En su primera edición no había advertencias sobre asignar a una variable un valor un tipo distinto. Por lo que había un programa llamado lint que detectaba este tipo de errores. Actualmente los compiladores pueden detectar inconsistencias de tipos y otros errores.

Usa un lenguaje de preprocesado, el preprocesador de C, para tareas como definir macros e incluir múltiples archivos de código fuente.

Acceso a memoria de bajo nivel mediante el uso de punteros.

Manejo de Interrupciones mediante la biblioteca signal.

Un conjunto reducido de palabras clave.

El llamado a funciones es por valor. Aunque se pueden pasar punteros a variables para hacer llamados por referencia.

Distintos tipos de almacenamiento que permiten un diseño modular.

La palabra clave static permite encapsular variables y funciones.

Las estructuras se declaran mediante la palabra clave struct, implementan el producto cartesiano de tipos también llamados registros.

Y la unión disyunta, también llamada suma, co-producto o tipos variantes, se declara con la palabra clave union. Las estructuras y uniones permiten la implementación de árboles.

Lenguaje muy eficiente puesto que es posible utilizar sus características de bajo nivel para realizar implementaciones óptimas.

Se diseñó como un lenguaje de programación de sistemas portátil.

Es muy poco lo que requiere uso de ensamblador, lo que permitió portar Unix y otros sistemas operativos a distintos equipos.

Distingue entre mayúsculas y minúsculas, pero conserva su portabilidad en equipos que manejan caracteres de 6 bits, como las computadoras Cyber de CDC que tenían una palabra de 60 bits, (10 caracteres), porque usan trigráficos para codificar símbolos especiales.

Su compilador de C se ha portado a casi todos los sistemas conocidos. Porque además de que no se requiere codificar en ensamblador, interactúa con los lenguajes especializados YACC y LEX. también escritos en C como parte de Unix.

Facilita la programación modular gracias a que cuenta con distintos tipos de almacenamiento de las variables y compilación separada. Además del macro procesador integrado cpp, que permite declarar los encabezados de las funciones y los tipos de datos en archivos con extensión h. En el caso de las bibliotecas del sistema Unix y de C se necesita incluir los prototipos con la macros #include por ejemplo #include <system.h>. Ello únicamente sirve para automatizar la declaración de objetos externos que se usarán en el programa, por lo que es necesario pasar los nombres de las bibliotecas como parámetros del compilador que este pasa al encadenador (linker loader).

Los programadores novatos deben tener cuidado con la gestión de la memoria, en C el programador ha de reservar y liberar la memoria explícitamente. En otros lenguajes (como C# o Java) la memoria es gestionada de forma transparente para el programador. Esto alivia la carga de trabajo y evita errores, pero le quita flexibilidad al lenguaje para escribir controladores del hardware.

Por esta razón es muy importante que los recién iniciados adopten buenas prácticas a la hora de escribir en C y manejar la memoria, como por ejemplo un uso intensivo de indentación y conocer a fondo todo lo que implica el manejo de punteros y direcciones de memoria.

Aunque la lista de las características útiles de las que carece C es larga, este factor ha sido importante para su aceptación, porque escribir rápidamente nuevos compiladores para nuevas plataformas, mantiene lo que realmente hace el programa bajo el control directo del programador, y permite implementar la solución más natural para cada plataforma. Esta es la causa de que a menudo C sea más eficiente que otros lenguajes. Típicamente, solo la programación cuidadosa en lenguaje ensamblador produce un código más rápido, pues da control total sobre la máquina, aunque los avances en los compiladores de C y la complejidad creciente de los microprocesadores modernos han reducido gradualmente esta diferencia.

El lenguaje se puede extender mediante bibliotecas y macros. Por ejemplo, la implementación original de C++ consistía en un preprocesador que traducía código fuente C++ a C.

El desarrollo inicial de C se llevó a cabo en los Laboratorios Bell de AT&T entre 1969 y 1973; según Dennis Ritchie, el periodo más creativo tuvo lugar en 1972. ​ Se le dio el nombre "C" porque muchas de sus características fueron tomadas de un lenguaje anterior llamado " B".

Hay muchas leyendas acerca del origen de C y el sistema operativo con el que está íntimamente relacionado, Unix. Algunas de ellas son:

El desarrollo de C fue el resultado del deseo de los programadores de jugar con Space Travel. Habían estado jugando en el mainframe de su compañía, pero debido a su poca capacidad de proceso y al tener que soportar 100 usuarios, Ken Thompson y Dennis Ritchie no tenían suficiente control sobre la nave para evitar colisiones con los asteroides, por ese motivo decidieron portar el juego a un PDP-7 de la oficina que no se utilizaba; pero esa máquina no tenía sistema operativo, así que decidieron escribir uno. Finalmente decidieron portar el sistema operativo del PDP-11 que había en su oficina, pero era muy costoso, pues todo el código estaba escrito en lenguaje ensamblador. Entonces decidieron usar un lenguaje de alto nivel y portátil para que el sistema operativo se pudiera portar fácilmente de un ordenador a otro, consideraron usar B pero carecía de las funcionalidades necesarias para aprovechar algunas características avanzadas del PDP-11 entonces empezaron a crear un nuevo lenguaje, C.

La justificación para obtener el ordenador original que se usó para desarrollar Unix fue crear un sistema que automatizase el archivo de patentes. La versión original de Unix se desarrolló en lenguaje ensamblador. Más tarde, el lenguaje C se desarrolló para poder reescribir el sistema operativo.

En 1973, el lenguaje C se había vuelto tan potente que la mayor parte del kernel Unix, originalmente escrito en el lenguaje ensamblador PDP-11, fue reescrita en C.​ Este fue uno de los primeros núcleos de sistema operativo implementados en un lenguaje distinto al ensamblador. (Algunos casos anteriores son el sistema Multics, escrito en PL/I, y Master Control Program para el B5000 de Burroughs, escrito en ALGOL en 1961).

En 1978, Ritchie y Brian Kernighan publicaron la primera edición de El lenguaje de programación C, también conocido como La biblia de C. Este libro fue durante años la especificación informal del lenguaje.​ El lenguaje descrito en este libro recibe habitualmente el nombre de "el C de Kernighan y Ritchie" o simplemente "K&R C" (La segunda edición del libro cubre el estándar ANSI C, descrito más abajo).

Kernighan y Ritchie introdujeron las siguientes características al lenguaje:

El tipo de datos struct.

El tipo de datos long int.

El tipo de datos unsigned int.

Los operadores =+ y =- fueron sustituidos por += y -= para eliminar la ambigüedad sintáctica de expresiones como i=-10, que se podría interpretar bien como i =- 10 o bien como i = -10.

El C de Kernighan y Ritchie es el subconjunto más básico del lenguaje que un compilador debe de soportar. Durante muchos años, incluso tras la introducción del ANSI C, fue considerado "el mínimo común denominador" en el que los programadores debían programar cuando deseaban que sus programas fueran transportables, pues no todos los compiladores soportaban completamente ANSI, y el código razonablemente bien escrito en K&R C es también código ANSI C válido.

En las primeras versiones del lenguaje, la definición de funciones se hacía mediante un 'prototipo de función' (function prototype), el cual indicaba al compilador el tipo de retorno de la función. Aunque este método tiene una gran desventaja respecto al nuevo, debido a que no comprueba el número ni el tipo en la lista de argumentos; en otras palabras, es mucho más fácil cometer errores al hacer una llamada a una función con argumentos incorrectos.

Ejemplo del "viejo estilo":

Ejemplo de la nueva definición:

(*) Por defecto, el tipo de retorno en C es int, por lo que la declaración entera int power(); podría haberse omitido.

En los años siguientes a la publicación del C de Kernighan y Ritchie, se añadieron al lenguaje muchas características no oficiales, que estaba soportadas por los compiladores de AT&T, entre otros. Algunas de estas características eran:

Funciones void y el tipo de datos void *.

Funciones que retornaban tipos de datos struct o union (en lugar de punteros).

Asignación de tipos de datos struct.

Calificador const, que hace que un objeto sea de solo lectura.

Una biblioteca estándar, que incorporaba la mayoría de las funcionalidades implementadas por varios desarrolladores de compiladores.

Enumeraciones.

A finales de la década de 1970, C empezó a sustituir a BASIC como lenguaje de programación de microcomputadores predominante. Durante la década de 1980 se empezó a usar en los IBM PC, lo que incrementó su popularidad significativamente. Al mismo tiempo, Bjarne Stroustrup empezó a trabajar con algunos compañeros de Bell Labs para añadir funcionalidades de programación orientada a objetos a C. El lenguaje que crearon, llamado C++, es hoy en día el lenguaje de programación de aplicaciones más común en el sistema operativo Microsoft Windows; mientras que C sigue siendo más popular en el entorno Unix. Otro lenguaje que se desarrolló en esa época, Objective C, también añadió características de programación orientada a objetos a C. Aunque hoy en día no es tan popular como C++, se usa para desarrollar aplicaciones Cocoa para Mac OS X.

En 1983, el Instituto Nacional Estadounidense de Estándares (ANSI) organizó un comité, X3j11, para establecer una especificación estándar de C. Tras un proceso largo y arduo, se completó el estándar en 1989 y se ratificó como el "Lenguaje de Programación C" ANSI X3.159-1989. Esta versión del lenguaje se conoce a menudo como ANSI C, o a veces como C89 (para distinguirla de C99).

En 1990, el estándar ANSI (con algunas modificaciones menores) fue adoptado por la Organización Internacional para la Estandarización (ISO) en el estándar ISO/IEC 9899:1990. Esta versión se conoce a veces como C90. No obstante, "C89" y "C90" se refieren en esencia al mismo lenguaje.

Uno de los objetivos del proceso de estandarización del ANSI C fue producir una extensión al C de Kernighan y Ritchie, incorporando muchas funcionalidades no oficiales. Sin embargo, el comité de estandarización incluyó también muchas funcionalidades nuevas, como prototipos de función, y un preprocesador mejorado. También se cambió la sintaxis de la declaración de parámetros para hacerla semejante a la empleada habitualmente en C++:

pasó a ser:

ANSI C está soportado hoy en día por casi la totalidad de los compiladores. La mayoría del código C que se escribe actualmente está basado en ANSI C. Cualquier programa escrito sólo en C estándar sin código que dependa de un hardware determinado funciona correctamente en cualquier plataforma que disponga de una implementación de C compatible. Sin embargo, muchos programas han sido escritos de forma que solo pueden compilarse en una cierta plataforma, o con un compilador concreto, esto puede ser debido a diversos motivos:

La utilización de bibliotecas no estándar, como interfaces gráficas de usuario.

El uso de compiladores que no cumplen las especificaciones del estándar.

El uso de tipos de datos suponiendo que tendrán el mismo tamaño u orden de los bits en todas las plataformas.

La macro __STDC__ puede usarse para dividir el código en secciones ANSI y K&R para el compilador.

Algunos programadores recomiendan usar "#if __STDC__", como en el ejemplo, en lugar de "#ifdef __STDC__" porque algunos compiladores le asignan el valor cero a __STDC__ para indicar que no son compatibles con ANSI.

En el siguiente ejemplo, el programa pide al usuario que introduzca un número. El programa dividirá dicho número entre 2 e imprimirá el resultado mientras que este sea par, y terminará cuando el número sea impar:

Palabras reservadas de ANSI-C

Para mejorarla, pulsa [editar] junto a su título: En esta sección se detectó el siguiente problema.

Podría contener información desactualizada.

Este aviso fue puesto el 7 de mayo de 2019.

Tras el proceso de estandarización de ANSI, la especificación del lenguaje C permaneció relativamente estable durante algún tiempo, mientras que C++ siguió evolucionando. Sin embargo, el estándar continuó bajo revisión a finales de la década de 1990, lo que llevó a la publicación del estándar ISO 9899:1999 en 1999.​ Este estándar se denomina habitualmente "C99". Se adoptó como estándar ANSI en marzo de 2000.

Las nuevas características de C99 incluyen:​

Funciones inline.

Las variables pueden declararse en cualquier sitio (como en C++), en lugar de poder declararse solo tras otra declaración o al comienzo de una declaración compuesta.

Muchos tipos de datos, incluyendo long int (para reducir el engorro de la transición de 32 bits a 64 bits), un tipo de dato booleano, y un tipo complex que representa números complejos.

Arrays de longitud variable.

Soporte para comentarios de una línea que empiecen con //, como en BCPL o en C++, característica para la que muchos compiladores habían dado soporte por su cuenta.

Muchas funciones nuevas, como snprintf()

Algunos headers nuevos, como stdint.h.

El compilador GCC, entre muchos otros, soportan hoy en día la mayoría de las nuevas características de C99. Sin embargo, este nuevo estándar ha tenido poca acogida entre algunos desarrolladores de compiladores, como Microsoft y Borland, que se han centrado en C++. Brandon Bray, de Microsoft, dijo a este respecto:

"En general, hemos visto poca demanda de muchas características de C99. Algunas características tienen más demanda que otras, y consideraremos incluirlas en versiones futuras siempre que sean compatibles con C++."​

C11 (antes conocido como C1X) es un nombre informal para ISO/IEC 9899:2011​. El borrador final, N1570, fue publicado en abril de 2011.​ El nuevo estándar superó su última revisión el 10 de octubre de 2011 y fue oficialmente ratificado por la ISO y publicado el 8 de diciembre de 2011.

Históricamente la programación en C embebido ha requerido extensiones no estándar del lenguaje C para implementar características no oficiales tales como aritmética de punto fijo y operaciones básicas de entrada y salida.

En 2008 el comité de estandarización de C, para implementar estas características no oficiales, publicó un informe técnico en el que extendía el lenguaje C proporcionando un estándar común al que todas las implementaciones se podían adherir. Incluía varias características no disponibles en C normal, tales como aritmética de punto fijo, espacios de direcciones con nombres y direccionamiento por hardware de entrada y salida básico.

El último estándar publicado para C ISO/IEC 9899:2018.​

Desde el inicio del lenguaje han surgido varias ramas de evolución que han generado varios lenguajes:

También se han creado numerosos lenguajes inspirados en la sintaxis de C, pero que no son compatibles con él:

La compilación de un programa C se realiza en varias fases que normalmente son automatizadas y ocultadas por los entornos de desarrollo:

1. Preprocesado consistente en modificar el código fuente en C según una serie de instrucciones (denominadas directivas de preprocesado) simplificando de esta forma el trabajo del compilador. Por ejemplo, una de las acciones más importantes es la modificación de las inclusiones (#include) por las declaraciones reales existentes en el archivo indicado.

2. Compilación que genera el código objeto a partir del código ya preprocesado.

3. que une los códigos objeto de los distintos módulos y bibliotecas externas (como las bibliotecas del sistema) con el código objeto generado en el paso anterior para generar el programa ejecutable final.

Ejemplo de código

El siguiente programa imprime en pantalla la frase "Hola Mundo" (C99).

El siguiente escribe "Hola Mundo" en C89

Estructura de control "else if"

Al programar en C, es habitual usar algunas herramientas de programación de uso muy extendido, sobre todo en entorno de tipo Unix:

make: automatizador del proceso de compilación y enlazado;

lint: detector de código sospechoso, confuso o incompatible entre distintas arquitecturas;

: detector de posibles fugas de memoria;

: depurador (debugger) usado en GNU;

dbx: depurador preinstalado en Unix;

: interfaz gráfico para los depuradores gdb o dbx.

Hecho principalmente para la fluidez de programación en sistemas Unix. Se usa también para el desarrollo de otros sistemas operativos como Windows o GNU/Linux. Igualmente para aplicaciones de escritorio como GIMP, cuyo principal lenguaje de programación es C.

De la misma forma, es muy usado en aplicaciones científicas (para experimentos informáticos, físicos, químicos, matemáticos, entre otros, parte de ellos conocidos como modelos y simuladores), industriales (industria robótica, cibernética, sistemas de información y base de datos para la industria petrolera y petroquímica. Predominan también todo lo que se refiere a simulación de máquinas de manufactura), simulaciones de vuelo (es la más delicada, ya que se tienen que usar demasiados recursos tanto de hardware como de software para desarrollar aplicaciones que permitan simular el vuelo real de una aeronave). Se aplica por tanto, en diversas áreas desconocidas por gran parte de los usuarios noveles.

Los ordenadores de finales de los 90 son varios órdenes de magnitud más potentes que las máquinas en que C se desarrolló originalmente. Programas escritos en lenguajes de tipo dinámico y fácil codificación ( Ruby, Python, Perl...) que antaño hubieran resultado demasiado lentos, son lo bastante rápidos como para desplazar en uso a C. Aun así, se puede seguir encontrando código C en grandes desarrollos de animaciones, modelados y escenas en 3D en películas y otras aplicaciones multimedia.

Actualmente, los grandes proyectos de software se dividen en partes, dentro de un equipo de desarrollo. Aquellas partes que son más "burocráticas" o "de gestión" con los recursos del sistema, se suelen realizar en lenguajes de tipo dinámico o de guion ( script), mientras que aquellas partes "críticas", por su necesidad de rapidez de ejecución, se realizan en un lenguaje de tipo compilado, como C o C++. Si, después de hacer la división, las partes críticas no superan un cierto porcentaje del total (aproximadamente el 10%) entonces todo el desarrollo se realiza con lenguajes dinámicos. Si la parte crítica no llega a cumplir las expectativas del proyecto, se comparan las alternativas de una inversión en nuevo hardware frente a invertir en el coste de un programador para que reescriba dicha parte crítica.

C es el lenguaje común para programar sistemas embebidos.[cita requerida] El código ligero que un compilador C genera, combinado con la capacidad de acceso a capas del software cercanas al hardware son la causa de su popularidad en estas aplicaciones.

Una característica donde C demuestra comodidad de uso particularmente valiosa en sistemas embebidos es la manipulación de bits. Los sistemas contienen registros mapeados en memoria (en inglés, MMR) a través de los cuales los periféricos se configuran. Estos registros mezclan varias configuraciones en la misma dirección de memoria, aunque en bits distintos. Con C es posible modificar fácilmente uno de estos bits sin alterar el resto. Por ejemplo:

Este tipo de manipulación es muy tediosa o sencillamente imposible en otros lenguajes de alto nivel, dado que se utilizan operaciones comunes del lenguaje ensamblador como las operaciones a nivel bit OR, AND, SHL y CPL pero que están disponibles en el lenguaje C.

Otras características de C consideradas desventajas en la programación para PC -como la ausencia de control de memoria automático- se convierten en ventajas cuando los sistemas embebidos necesitan código pequeño y optimizado. Ese es el caso de los sistemas basados en microcontroladores de poca potencia como el intel 8051 o muchos sistemas ARM.

Una biblioteca de C es una colección de funciones utilizadas en el lenguaje de programación C. Las bibliotecas más comunes son la biblioteca estándar de C y la biblioteca del estándar ANSI C, la cual provee las especificaciones de los estándares que son ampliamente compartidas entre bibliotecas. La biblioteca ANSI C estándar, incluye funciones para la entrada y salida de archivos, alojamiento de memoria y operaciones con datos comunes: funciones matemáticas, funciones de manejo de cadenas de texto y funciones de hora y fecha.

Otras bibliotecas C son aquellas utilizadas para desarrollar sistemas Unix, las cuales proveen interfaces hacia el núcleo. Estas funciones son detalladas en varios estándares tales como POSIX y el Single UNIX Specification.

Ya que muchos programas han sido escritos en el lenguaje C existe una gran variedad de bibliotecas disponibles. Muchas bibliotecas son escritas en C debido a que C genera código objeto rápido; los programadores luego generan interfaces a la biblioteca para que las rutinas puedan ser utilizadas desde lenguajes de mayor nivel, tales como Java, Perl y Python.

# data[].attributes.attachment_link.title
C (lenguaje de programación) - Wikipedia, la enciclopedia libre

# data[].attributes.attachment_link.description
Por favor, En este artículo se detectaron varios problemas. edítalo para mejorarlo: Este aviso fue puesto el 4 de mayo de 2019. C Desarrollador(es) Dennis Ritchie y Laboratorios Bell Información general Extensiones comunes .c, .h Paradigma Imperativo ( procedural), estructurado Apareció en 1972 Diseñado por Dennis Ritchie Última versión estable C18 (junio de 2018) Última versión en pruebas C2x Sistema de tipos Débil, estático Implementaciones GCC, Intel C, entre muchas más.

# data[].attributes.attachment_link.description
Larry Wall comenzó a trabajar en Perl en 1987 mientras trabajaba como programador en Unisys​ y anunció la versión 1.0 en el grupo de noticias comp.sources.misc el 18 de diciembre de 1987. El lenguaje se expandió rápidamente en los siguientes años. Perl 2, publicado en 1988, aportó un mejor motor de expresiones regulares.

# data[].attributes.attachment_link.readable_text
Paradigm

Multi-paradigm: imperative, functional, object-oriented, procedural, reflective

Designed by
Rasmus Lerdorf

Developer

The PHP Development Team, Zend Technologies, PHP Foundation

First appeared

8 June 1995; 28 years ago [1][2]

Stable release

8.3.0

8.2.13 8.1.26

/ 23 November 2023; 8 days ago [3]

Typing discipline

Dynamic, weak, gradual[4]

Implementation language

C (primarily; some components C++)

OS

Unix-like, Windows, macOS, IBM i, OpenVMS

License

dual licensed GNU General Public License version 2 or any later version and PHP License for PHP versions 3.0 or earlier.[5] Only PHP License (most of Zend engine under Zend Engine License) for 3.01x and later versions.

Filename extensions

.php,.phar,.phtml,.pht,.phps

Website

www.php.net

Zend Engine, HHVM, PeachPie, Quercus, Parrot

Perl, C, C++, Java,[6] Tcl,[2] JavaScript[7]

Hack, JSP, ASP, React JS

PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. PHP was originally an abbreviation of Personal Home Page, but it now stands for the recursive initialism PHP: Hypertext Preprocessor.

PHP code is usually processed on a web server by a PHP interpreter implemented as a module, a daemon or a Common Gateway Interface (CGI) executable. On a web server, the result of the interpreted and executed PHP code-which may be any type of data, such as generated HTML or binary image data-would form the whole or part of an HTTP response. Various web template systems, web content management systems, and web frameworks exist that can be employed to orchestrate or facilitate the generation of that response. Additionally, PHP can be used for many programming tasks outside the web context, such as standalone graphical applications and robotic drone control. PHP code can also be directly executed from the command line.

The standard PHP interpreter, powered by the Zend Engine, is free software released under the PHP License. PHP has been widely ported and can be deployed on most web servers on a variety of operating systems and platforms.

The PHP language has evolved without a written formal specification or standard, with the original implementation acting as the standard that other implementations aimed to follow.

W3Techs reports that as of December 2023, "PHP is used by 76.6% of all the websites whose server-side programming language we know." It also reports that:

20.1% of PHP users use 8.x versions (most thereof on 8.0 with is no longer supported);

61.3% - most by far use the unsupported PHP 7, more specifically PHP 7.4;

18.3% use PHP 5, which is neither supported with security fixes and is known to have serious security vulnerabilities.

This means the vast majority of PHP websites, e.g. all PHP 7 and PHP 5 websites are vulnerable to hacking; some Linux distributions such as Ubuntu and Debian provide commercial support, and may provide paid-for security patches for e.g. 7.4 of PHP.

PHP development began in 1993 when Rasmus Lerdorf wrote several Common Gateway Interface (CGI) programs in C, which he used to maintain his personal homepage. He extended them to work with web forms and to communicate with databases, and called this implementation "Personal Home Page/Forms Interpreter" or PHP/FI.

PHP/FI could be used to build simple, dynamic web applications. To accelerate bug reporting and improve the code, Lerdorf initially announced the release of PHP/FI as "Personal Home Page Tools (PHP Tools) version 1.0" on the Usenet discussion group comp.infosystems.www.authoring.cgi on 8 June 1995. This release already had the basic functionality that PHP has today. This included Perl-like variables, form handling, and the ability to embed HTML. The syntax resembled that of Perl, but was simpler, more limited and less consistent.

An example of the early PHP syntax:

Early PHP was not intended to be a new programming language, and grew organically, with Lerdorf noting in retrospect: "I don't know how to stop it, there was never any intent to write a programming language [...] I have absolutely no idea how to write a programming language, I just kept adding the next logical step on the way." A development team began to form and, after months of work and beta testing, officially released PHP/FI 2 in November 1997.

The fact that PHP was not originally designed, but instead was developed organically has led to inconsistent naming of functions and inconsistent ordering of their parameters. In some cases, the function names were chosen to match the lower-level libraries which PHP was "wrapping", while in some very early versions of PHP the length of the function names was used internally as a hash function, so names were chosen to improve the distribution of hash values.

This is an example of PHP code for the WordPress content management system.

Zeev Suraski and Andi Gutmans rewrote the parser in 1997 and formed the base of PHP 3, changing the language's name to the recursive acronym PHP: Hypertext Preprocessor. Afterwards, public testing of PHP 3 began, and the official launch came in June 1998. Suraski and Gutmans then started a new rewrite of PHP's core, producing the Zend Engine in 1999. They also founded Zend Technologies in Ramat Gan, Israel.

On 22 May 2000, PHP 4, powered by the Zend Engine 1.0, was released. By August 2008, this branch had reached version 4.4.9. PHP 4 is now no longer under development and nor are any security updates planned to be released.

On 1 July 2004, PHP 5 was released, powered by the new Zend Engine II. PHP 5 included new features such as improved support for object-oriented programming, the PHP Data Objects (PDO) extension (which defines a lightweight and consistent interface for accessing databases), and numerous performance enhancements. In 2008, PHP 5 became the only stable version under development. Late static binding had been missing from previous versions of PHP, and was added in version 5.3.

Many high-profile open-source projects ceased to support PHP 4 in new code from February 5, 2008, because of the GoPHP5 initiative, provided by a consortium of PHP developers promoting the transition from PHP 4 to PHP 5.

Over time, PHP interpreters became available on most existing 32-bit and 64-bit operating systems, either by building them from the PHP source code or by using pre-built binaries. For PHP versions 5.3 and 5.4, the only available Microsoft Windows binary distributions were 32-bit IA-32 builds, requiring Windows 32-bit compatibility mode while using Internet Information Services (IIS) on a 64-bit Windows platform. PHP version 5.5 made the 64-bit x86-64 builds available for Microsoft Windows.

Official security support for PHP 5.6 ended on 31 December 2018.

PHP received mixed reviews due to lacking native Unicode support at the core language level. In 2005, a project headed by Andrei Zmievski was initiated to bring native Unicode support throughout PHP, by embedding the International Components for Unicode (ICU) library, and representing text strings as UTF-16 internally. Since this would cause major changes both to the internals of the language and to user code, it was planned to release this as version 6.0 of the language, along with other major features then in development.

However, a shortage of developers who understood the necessary changes, and performance problems arising from conversion to and from UTF-16, which is rarely used in a web context, led to delays in the project. As a result, a PHP 5.3 release was created in 2009, with many non-Unicode features back-ported from PHP 6, notably namespaces. In March 2010, the project in its current form was officially abandoned, and a PHP 5.4 release was prepared to contain most remaining non-Unicode features from PHP 6, such as traits and closure re-binding. Initial hopes were that a new plan would be formed for Unicode integration, but by 2014 none had been adopted.

During 2014 and 2015, a new major PHP version was developed, PHP 7, and it's still the most used PHP version, more much more popular than its successor. The numbering of this version involved some debate among internal developers. While the PHP 6 Unicode experiments had never been released, several articles and book titles referenced the PHP 6 names, which might have caused confusion if a new release were to reuse the name. After a vote, the name PHP 7 was chosen.

The foundation of PHP 7 is a PHP branch that was originally dubbed PHP next generation ( phpng). It was authored by Dmitry Stogov, Xinchen Hui and Nikita Popov, and aimed to optimize PHP performance by refactoring the Zend Engine while retaining near-complete language compatibility. By 14 July 2014, WordPress-based benchmarks, which served as the main benchmark suite for the phpng project, showed an almost 100% increase in performance. Changes from phpng make it easier to improve performance in future versions, as more compact data structures and other changes are seen as better suited for a successful migration to a just-in-time (JIT) compiler. Because of the significant changes, the reworked Zend Engine was called Zend Engine 3, succeeding Zend Engine 2 used in PHP 5.

Because of the major internal changes in phpng, it must receive a new major version number of PHP, rather than a minor PHP 5 release, according to PHP's release process. Major versions of PHP are allowed to break backward-compatibility of code and therefore PHP 7 presented an opportunity for other improvements beyond phpng that require backward-compatibility breaks. In particular, it involved the following changes:

Many fatal or recoverable-level legacy PHP error mechanisms were replaced with modern object-oriented exceptions.

The syntax for variable dereferencing was reworked to be internally more consistent and complete, allowing the use of the operators ->, [], (),{}, and ::, with arbitrary meaningful left-side expressions.

Support for legacy PHP 4-style constructor methods was deprecated.

The behavior of the foreach statement was changed to be more predictable.

Constructors for the few classes built-in to PHP which returned null upon failure were changed to throw an exception instead, for consistency.

Several unmaintained or deprecated server application programming interfaces (SAPIs) and extensions were removed from the PHP core, most notably the legacy mysql extension.

The behavior of the list() operator was changed to remove support for strings.

An oversight allowing a switch statement to have multiple default clauses was fixed.

Support for hexadecimal number support in some implicit conversions from strings to number types was removed.

The left-shift and right-shift operators were changed to behave more consistently across platforms.

Conversions between floating-point numbers and integers were changed (e.g. infinity changed to convert to zero) and implemented more consistently across platforms.

PHP 7 also included new language features. Most notably, it introduced return type declarations for functions which complement the existing parameter type declarations, and support for the scalar types (integer, float, string, and boolean) in parameter and return type declarations.

PHP 8 was released on 26 November 2020, and is currently the second-most used PHP major version. PHP 8 is a major version and has breaking changes from previous versions. New features and notable changes include:

Just-in-time compilation is supported in PHP 8.

PHP 8's JIT compiler can provide substantial performance improvements for some use cases, while PHP developer Nikita Popov stated that the performance improvements for most websites will be less substantial than the upgrade from PHP 5 to PHP 7. Substantial improvements are expected more for mathematical-type operations than for common web-development use cases. Additionally, the JIT compiler provides the future potential to move some code from C to PHP, due to the performance improvements for some use cases.

PHP 8 introduced the match expression. The match expression is conceptually similar to a switch statement and is more compact for some use cases. Because match is an expression, its result can be assigned to a variable or returned from a function.

PHP 8 introduced union types, a new static return type, and a new mixed type.

"Attributes", often referred to as "annotations" in other programming languages, were added in PHP 8, which allow metadata to be added to classes.

throw was changed from being a statement to being an expression. This allows exceptions to be thrown in places that were not previously possible.

PHP 8 includes changes to allow alternate, more concise, or more consistent syntaxes in a number of scenarios. For example, the nullsafe operator is similar to the null coalescing operator ??, but used when calling methods. The following code snippet will not throw an error if getBirthday() returns null:

Constructor property promotion has been added as " syntactic sugar," allowing class properties to be set automatically when parameters are passed into a class constructor. This reduces the amount of boilerplate code that must be written.

Other minor changes include support for use of ::class on objects, which serves as an alternative for the use of get_class(); non-capturing catches in try-catch blocks; variable syntax tweaks to resolve inconsistencies; support for named arguments; and support for trailing commas in parameter lists, which adds consistency with support for trailing commas in other contexts, such as in arrays.

Weak maps were added in PHP 8. A WeakMap holds references to objects, but these references do not prevent such objects from being garbage collected. This can provide performance improvements in scenarios where data is being cached; this is of particular relevance for object-relational mappings (ORM).

Various adjustments to interfaces, such as adding support for creating DateTime objects from interfaces, and the addition of a Stringable interface that can be used for type hinting.[citation needed ]

Various new functions including str_contains(), str_starts_with(), and str_ends_with(); fdiv(); get_debug_type(); and get_resource_id()[citation needed ]

Object implementation of token_get_all()[citation needed ]

Type annotations were also added into PHP's C source code itself to allow internal functions and methods to have "complete type information in reflection."

Inheritance with private methods[citation needed ]

Abstract methods in traits improvements[citation needed ]

PHP 8.1 was released on 8 December 2021, and included a number of new features and improvements over previous versions. Here is a more detailed look at some of the key features and improvements in PHP 8.1:

Union types: This feature allows you to specify that a variable can have multiple types, such as an integer or a string. This can be useful for writing more flexible and robust code, as it allows you to handle a wider range of input values.

Nullsafe operator: This operator allows you to chain method calls without worrying about null references. For example, if you want to call a method on an object that may be null, you can use the null safe operator to ensure that the method is only called if the object is not null.

Match expression: This is a more concise and flexible way to perform matching on values. It allows you to specify multiple cases and their associated values, and then use the match keyword to select the appropriate case based on the value of an expression.

Improved performance: PHP 8.1 includes various performance improvements, such as faster array operations and better memory usage. These improvements can help make your code run faster and more efficiently.

New error handling features: PHP 8.1 introduces a new throws keyword that allows you to specify which exceptions a function can throw, and a new assert() function that can be used to check for certain conditions at runtime. These features can help you write more reliable and robust code.

Other new features: PHP 8.1 also includes other new features such as support for named arguments, support for attributes (similar to annotations in other languages), and improved support for Unicode.

The match expression is a new feature in PHP 8.1 that allows you to perform value matching in a more concise and flexible way. It is similar to a switch statement, but with some additional features and syntax improvements.

Here is an example of how you can use the match expression in PHP:

In this example, the match expression compares the value of $value to the different cases specified in the curly braces. If $value matches one of the cases, the corresponding value is returned. If none of the cases matches, the default case is used.

One of the main benefits of the match expression is that it allows you to specify multiple values for a single case, as shown in the example above. This can help make your code more concise and easier to read.

Assert() Error handling

The assert() function and the throws keyword are new error-handling features in PHP 8.1 that can help you write more reliable and robust code.

The assert() function is used to check for certain conditions at runtime. If the condition is not met, the function generates an AssertionError exception. For example:

In this example, the assert() function checks whether $x is greater than zero. If it is not, an AssertionError exception is thrown with the message "$x must be greater than zero".

The throws keyword, on the other hand, is used to specify which exceptions a function or method can throw. This can be helpful for documenting your code and making it easier for other developers to understand how your functions and methods behave. For example:

In this example, the divide() function uses the throws keyword to specify that it can throw a DivisionByZeroError exception if the second argument is zero.

Overall, the assert() function and the throws keyword are useful tools for handling errors and exceptions in PHP and can help you write more reliable and robust code.

Support for enumerations was one of the most prominent features of PHP 8.1. Enums allow developers to programmatically enforce states in their codebase. Below is an example of an enum:

Support for 'read-only' properties was added.

After the introduction of array unpacking in PHP 7.4 with consecutively numbered keys, PHP 8.1 introduced support for array unpacking with string keys.

PHP 8.1 added support for using 'new' in initializers.

A new syntax was added for creating callables.

PHP 8.1 brought support for Pure Intersection Types, after the introduction of union types in PHP 8.0.

PHP 8.2 includes a number of new features and improvements. Here are some of the main ones:

1. Improved Type Variance: PHP 8.2 introduces improved type variance for generic types, allowing you to specify whether a generic type is covariant, contravariant, or invariant. This can help to improve type safety and flexibility when working with generic types.

2. Performance Improvements: PHP 8.2 includes various performance improvements, including faster JIT compilation, faster garbage collection, and improved handling of large arrays. These improvements can help to make PHP applications faster and more efficient.

3. Deprecations: Some features have been deprecated in PHP 8.2, including the assert() function when used with a string argument, and the list() construct with a single array element. It's important to be aware of these deprecations if you are upgrading from an earlier version of PHP.

Here are some examples of features that have been deprecated in PHP 8.2:

1. assert() function with string argument: The assert() function can be used to perform runtime checks, but it has been deprecated when used with a string argument. Instead, you should use the assert() function with a boolean argument or an expression.

2. list() construct with a single array element: The list() construct allows you to unpack the elements of an array into separate variables. It has been deprecated when used with a single array element, as this usage was considered confusing and error-prone.

3. create_function(): The create_function() function has been deprecated, as it has been superseded by anonymous functions, which are more flexible and easier to use.

4. mb_ereg_replace_callback(): The mb_ereg_replace_callback() function has been deprecated, as it has been superseded by the preg_replace_callback() function, which provides similar functionality and is more widely used.

5. Callables that are not accepted by the $callable() syntax (but are accepted by call_user_func()) are deprecated.

New "Random" extension

The "Random" extension provides a new object-oriented API for generating random values in PHP. It includes several classes ("Engine"s) that implement different algorithms for generating random numbers and storing their state within objects. This allows for multiple independent seedable sequences, which can be useful in certain contexts, such as testing or simulation.

The \Random\Randomizer class provides a high-level interface for using the engine's randomness to generate a random integer, shuffle an array or string, select random array keys, and more. This can be a convenient way to perform these common tasks without having to directly use the lower-level engine classes.

It's worth noting that the "Random" extension is not enabled by default in PHP, and you will need to install and enable it in your PHP environment in order to use its features. You can find more information about the extension in the official PHP documentation.

1.0

8 June 1995

Officially called "Personal Home Page Tools (PHP Tools)". This is the first use of the name "PHP".

2.0

1 November 1997

Officially called "PHP/FI 2.0". This is the first release that could actually be characterised as PHP, being a standalone language with many features that have endured to the present day.

3.0

6 June 1998

Development moves from one person to multiple developers. Zeev Suraski and Andi Gutmans rewritten the base for this version.

4.2

Disabled register_globals by default. Data received over the network is not inserted directly into the global namespace anymore, closing possible security holes in applications.

4.4

Fixed a memory corruption bug, which required breaking binary compatibility with extensions compiled against PHP version 4.3.x.

5.1

Performance improvements with the introduction of compiler variables in re-engineered PHP Engine. Added PHP Data Objects (PDO) as a consistent interface for accessing databases.

5.3

Namespace support; late static bindings, jump label (limited goto), anonymous functions, closures, PHP archives (phar), garbage collection for circular references, improved Windows support, sqlite3, mysqlnd as a replacement for libmysql as the underlying library for the extensions that work with MySQL, fileinfo as a replacement for mime_magic for better MIME support, the Internationalization extension, and deprecation of ereg extension.

5.4

Trait support, short array syntax support. Removed items: register_globals, safe_mode, allow_call_time_pass_reference, , and . Built-in web server. Several improvements to existing features, performance and reduced memory requirements.

5.5

Support for generators, finally blocks for exceptions handling, OpCache (based on Zend Optimizer+) bundled in official distribution.

5.6

Constant scalar expressions, variadic functions, argument unpacking, new exponentiation operator, extensions of the use statement for functions and constants, new phpdbg debugger as a SAPI module, and other smaller improvements.

6.x

Not released

-

Abandoned version of PHP that planned to include native Unicode support.

7.0

Zend Engine 3 (performance improvements and 64-bit integer support on Windows), uniform variable syntax, AST-based compilation process, added , bitwise shift consistency across platforms, ( null coalesce) operator, Unicode code point escape syntax, return type declarations, scalar type (integer, float, string and boolean) declarations, <=> "spaceship" three-way comparison operator, generator delegation, anonymous classes, simpler and more consistently available CSPRNG API, replacement of many remaining internal PHP "errors" with the more modern exceptions, and shorthand syntax for importing multiple items from a namespace.

7.2

30 November 2017

Object parameter and return type declaration, Libsodium extension, abstract method overriding, parameter type widening

7.3

6 December 2021

Flexible Heredoc and Nowdoc syntax, support for reference assignment and array deconstruction with list(), PCRE2 support, hrtime() function

7.4

28 November 2022

Typed properties 2.0, preloading, null-coalescing assignment operator, improve openssl_random_pseudo_bytes, Weak References, FFI - foreign function interface, always available hash extension, password hash registry, multibyte string splitting, reflection for references, unbundle ext/wddx, new custom object serialization mechanism

8.0

26 November 2023

Just-In-Time (JIT) compilation, arrays starting with a negative index, stricter/saner language semantics (validation for abstract trait methods), saner string to number comparisons, saner numeric strings, TypeError on invalid arithmetic/bitwise operators, reclassification of various engine errors, consistent type errors for internal functions, fatal error for incompatible method signatures), locale-independent float to string conversion, variable syntax tweaks, attributes, named arguments, match expression, constructor property promotion, union types, mixed type, static return type, nullsafe operator, non-capturing catches, throw expression, JSON extension is always available.

Beginning on 28 June 2011, the PHP Development Team implemented a timeline for the release of new versions of PHP. Under this system, at least one release should occur every month. Once per year, a minor release should occur which may include new features. Every minor release should at least be supported for two years with security and bug fixes, followed by at least one year of only security fixes, for a total of a three-year release process for every minor release. No new features, unless small and self-contained, are to be introduced into a minor release during the three-year release process.

The elePHPant, PHP mascot

The mascot of the PHP project is the elePHPant, a blue elephant with the PHP logo on its side, designed by Vincent Pontier in 1998. "The (PHP) letters were forming the shape of an elephant if viewed in a sideways angle." The elePHPant is sometimes differently coloured when in plush toy form.

Many variations of this mascot have been made over the years. Only the elePHPants based on the original design by Vincent Pontier are considered official by the community. These are collectable and some of them are extremely rare.

A "Hello World" application in PHP 7.4 running on its built-in development server

The following "Hello, World!" program is written in PHP code embedded in an HTML document:

However, as no requirement exists for PHP code to be embedded in HTML, the simplest version of Hello, World! may be written like this, with the closing tag omitted as preferred in files containing pure PHP code.

The PHP interpreter only executes PHP code within its delimiters. Anything outside of its delimiters is not processed by PHP, although the non-PHP text is still subject to control structures described in PHP code. The most common delimiters are to open and to close PHP sections. The shortened form also exists. This short delimiter makes script files less portable since support for them can be disabled in the local PHP configuration and it is therefore discouraged. Conversely, there is no recommendation against the echo short tag . Prior to PHP 5.4.0, this short syntax for only works with the short_open_tag configuration setting enabled, while for PHP 5.4.0 and later it is always available. The purpose of all these delimiters is to separate PHP code from non-PHP content, such as JavaScript code or HTML markup. So the shortest "Hello, World!" program written in PHP is:

The first form of delimiters, and , in XHTML and other XML documents, creates correctly formed XML processing instructions. This means that the resulting mixture of PHP code and other markups in the server-side file is itself well-formed XML.

Variables are prefixed with a dollar symbol, and a type does not need to be specified in advance. PHP 5 introduced type declarations that allow functions to force their parameters to be objects of a specific class, arrays, interfaces or callback functions. However, before PHP 7, type declarations could not be used with scalar types such as integers or strings.

Below is an example of how PHP variables are declared and initialized.

Unlike function and class names, variable names are case-sensitive. Both double-quoted ("") and heredoc strings provide the ability to interpolate a variable's value into the string. PHP treats newlines as whitespace in the manner of a free-form language, and statements are terminated by a semicolon. PHP has three types of comment syntax: marks block and inline comments; or are used for one-line comments. The echo statement is one of several facilities PHP provides to output text.

In terms of keywords and language syntax, PHP is similar to C-style syntax. conditions, and loops and function returns are similar in syntax to languages such as C, C++, C#, Java and Perl.

PHP is loosely typed. It stores integers in a platform-dependent range, either as a 32, 64 or 128-bit signed integer equivalent to the C-language long type. Unsigned integers are converted to signed values in certain situations, which is different behaviour to many other programming languages. Integer variables can be assigned using decimal (positive and negative), octal, hexadecimal, and binary notations.

Floating-point numbers are also stored in a platform-specific range. They can be specified using floating-point notation, or two forms of scientific notation. PHP has a native Boolean type that is similar to the native Boolean types in Java and C++. Using the Boolean type conversion rules, non-zero values are interpreted as true and zero as false, as in Perl and C++.

The null data type represents a variable that has no value; NULL is the only allowed value for this data type.

Variables of the "resource" type represent references to resources from external sources. These are typically created by functions from a particular extension, and can only be processed by functions from the same extension; examples include file, image, and database resources.

Arrays can contain elements of any type that PHP can handle, including resources, objects, and even other arrays. Order is preserved in lists of values and in hashes with both keys and values, and the two can be intermingled. PHP also supports strings, which can be used with single quotes, double quotes, nowdoc or heredoc syntax.

The Standard PHP Library (SPL) attempts to solve standard problems and implements efficient data access interfaces and classes.

PHP defines a large array of functions in the core language and many are also available in various extensions; these functions are well documented online PHP documentation. However, the built-in library has a wide variety of naming conventions and associated inconsistencies, as described under history above.

Custom functions may be defined by the developer:

As of 2023, the output of the above sample program is "I am currently 28 years old."

In lieu of function pointers, functions in PHP can be referenced by a string containing their name. In this manner, normal PHP functions can be used, for example, as callbacks or within function tables. User-defined functions may be created at any time without being prototyped. Functions may be defined inside code blocks, permitting a run-time decision as to whether or not a function should be defined. There is a function_exists function that determines whether a function with a given name has already been defined. Function calls must use parentheses, with the exception of zero-argument class constructor functions called with the PHP operator new, in which case parentheses are optional.

Since PHP 4.0.1 create_function(), a thin wrapper around eval(), allowed normal PHP functions to be created during program execution; it was deprecated in PHP 7.2 and removed in PHP 8.0 in favor of syntax for anonymous functions or " closures" that can capture variables from the surrounding scope, which was added in PHP 5.3. Shorthand arrow syntax was added in PHP 7.4:

In the example above, getAdder() function creates a closure using passed argument , which takes an additional argument , and returns the created closure to the caller. Such a function is a first-class object, meaning that it can be stored in a variable, passed as a parameter to other functions, etc.

Unusually for a dynamically typed language, PHP supports type declarations on function parameters, which are enforced at runtime. This has been supported for classes and interfaces since PHP 5.0, for arrays since PHP 5.1, for "callables" since PHP 5.4, and scalar (integer, float, string and boolean) types since PHP 7.0. PHP 7.0 also has type declarations for function return types, expressed by placing the type name after the list of parameters, preceded by a colon. For example, the getAdder function from the earlier example could be annotated with types like so in PHP 7:

By default, scalar type declarations follow weak typing principles. So, for example, if a parameter's type is int, PHP would allow not only integers, but also convertible numeric strings, floats or booleans to be passed to that function, and would convert them. However, PHP 7 has a "strict typing" mode which, when used, disallows such conversions for function calls and returns within a file.

Basic object-oriented programming functionality was added in PHP 3 and improved in PHP 4. This allowed for PHP to gain further abstraction, making creative tasks easier for programmers using the language. Object handling was completely rewritten for PHP 5, expanding the feature set and enhancing performance. In previous versions of PHP, objects were handled like value types. The drawback of this method was that code had to make heavy use of PHP's "reference" variables if it wanted to modify an object it was passed rather than creating a copy of it. In the new approach, objects are referenced by handle, and not by value.

PHP 5 introduced private and protected member variables and methods, along with abstract classes, final classes, abstract methods, and final methods. It also introduced a standard way of declaring constructors and destructors, similar to that of other object-oriented languages such as C++, and a standard exception handling model. Furthermore, PHP 5 added interfaces and allowed for multiple interfaces to be implemented. There are special interfaces that allow objects to interact with the runtime system. Objects implementing ArrayAccess can be used with array syntax and objects implementing Iterator or IteratorAggregate can be used with the foreach language construct. There is no virtual table feature in the engine, so static variables are bound with a name instead of a reference at compile time.

If the developer creates a copy of an object using the reserved word clone, the Zend engine will check whether a __clone() method has been defined. If not, it will call a default __clone() which will copy the object's properties. If a __clone() method is defined, then it will be responsible for setting the necessary properties in the created object. For convenience, the engine will supply a function that imports the properties of the source object, so the programmer can start with a by-value replica of the source object and only override properties that need to be changed.

The visibility of PHP properties and methods is defined using the keywords public, private, and protected. The default is public, if only var is used; var is a synonym for public. Items declared public can be accessed everywhere. protected limits access to inherited classes (and to the class that defines the item). private limits visibility only to the class that defines the item. Objects of the same type have access to each other's private and protected members even though they are not the same instance.

The following is a basic example of object-oriented programming in PHP 8:

This program outputs the following:

Students:
Hello, my name is Alice, I learn Computer Science
Hello, my name is Bob, I learn Computer Science
Hello, my name is Charlie, I learn Business Studies
Teachers:
Hello, my name is Dan, I teach Computer Science, Information Security
Hello, my name is Erin, I teach Computer Science, 3D Graphics Programming
Hello, my name is Frankie, I teach Online Marketing, Business Studies, E-commerce

The only complete PHP implementation is the original, known simply as PHP. It is the most widely used and is powered by the Zend Engine. To disambiguate it from other implementations, it is sometimes unofficially called "Zend PHP". The Zend Engine compiles PHP source code on-the-fly into an internal format that it can execute, thus it works as an interpreter. It is also the "reference implementation" of PHP, as PHP has no formal specification, and so the semantics of Zend PHP define the semantics of PHP. Due to the complex and nuanced semantics of PHP, defined by how Zend works, it is difficult for competing implementations to offer complete compatibility.

PHP's single-request-per-script-execution model, and the fact that the Zend Engine is an interpreter, leads to inefficiency; as a result, various products have been developed to help improve PHP performance. In order to speed up execution time and not have to compile the PHP source code every time the web page is accessed, PHP scripts can also be deployed in the PHP engine's internal format by using an opcode cache, which works by caching the compiled form of a PHP script (opcodes) in shared memory to avoid the overhead of parsing and compiling the code every time the script runs. An opcode cache, Zend Opcache, is built into PHP since version 5.5. Another example of a widely used opcode cache is the Alternative PHP Cache (APC), which is available as a PECL extension.

While Zend PHP is still the most popular implementation, several other implementations have been developed. Some of these are compilers or support JIT compilation, and hence offer performance benefits over Zend PHP at the expense of lacking full PHP compatibility. Alternative implementations include the following:

HHVM (HipHop Virtual Machine) - developed at Facebook and available as open source, it converts PHP code into a high-level bytecode (commonly known as an intermediate language), which is then translated into x86-64 machine code dynamically at runtime by a just-in-time (JIT) compiler, resulting in up to 6× performance improvements. However, since version 7.2 Zend has outperformed HHVM, and HHVM 3.24 is the last version to officially support PHP.
HipHop - developed at Facebook and available as open source, it transforms the PHP scripts into C++ code and then compiles the resulting code, reducing the server load up to 50%. In early 2013, Facebook deprecated it in favour of HHVM due to multiple reasons, including deployment difficulties and lack of support for the whole PHP language, including the create_function() and eval() constructs.

Parrot - a virtual machine designed to run dynamic languages efficiently; the cross-translator Pipp transforms the PHP source code into the Parrot intermediate representation, which is then translated into the Parrot's bytecode and executed by the virtual machine.

PeachPie - a second-generation compiler to .NET Common Intermediate Language (CIL) bytecode, built on the Roslyn platform; successor of Phalanger, sharing several architectural components

Phalanger - compiles PHP into .Net Common Intermediate Language bytecode; predecessor of PeachPie

Quercus - compiles PHP into Java bytecode

PHP is free software released under the PHP License, which stipulates that:

Products derived from this software may not be called "PHP", nor may "PHP" appear in their name, without prior written permission from group@php.net. You may indicate that your software works in conjunction with PHP by saying " Foo for PHP" instead of calling it "PHP Foo" or "phpfoo".

This restriction on the use of "PHP" makes the PHP License incompatible with the General Public License (GPL), while the Zend License is incompatible due to an advertising clause similar to that of the original BSD license.

PHP includes various free and open-source libraries in its source distribution or uses them in resulting PHP binary builds. PHP is fundamentally an Internet-aware system with built-in modules for accessing File Transfer Protocol (FTP) servers and many database servers, including PostgreSQL, MySQL, Microsoft SQL Server and SQLite (which is an embedded database), LDAP servers, and others. Numerous functions are familiar to C programmers, such as those in the stdio family, are available in standard PHP builds.

PHP allows developers to write extensions in C to add functionality to the PHP language. PHP extensions can be compiled statically into PHP or loaded dynamically at runtime. Numerous extensions have been written to add support for the Windows API, process management on Unix-like operating systems, multibyte strings ( Unicode), cURL, and several popular compression formats. Other PHP features made available through extensions include integration with Internet Relay Chat (IRC), dynamic generation of images and Adobe Flash content, PHP Data Objects (PDO) as an abstraction layer used for accessing databases, and even speech synthesis. Some of the language's core functions, such as those dealing with strings and arrays, are also implemented as extensions. The PHP Extension Community Library (PECL) project is a repository for extensions to the PHP language.

Some other projects, such as Zephir, provide the ability for PHP extensions to be created in a high-level language and compiled into native PHP extensions. Such an approach, instead of writing PHP extensions directly in C, simplifies the development of extensions and reduces the time required for programming and testing.

By December 2018 the PHP Group consisted of ten people: Thies C. Arntzen, Stig Bakken, Shane Caraveo, Andi Gutmans, Rasmus Lerdorf, Sam Ruby, Sascha Schumann, Zeev Suraski, Jim Winstead, and Andrei Zmievski.

Zend Technologies provides a PHP Certification based on PHP 7 exam (and previously based on PHP 5.5) for programmers to become certified PHP developers.

On 26 November 2021, the JetBrains blog announced the creation of the PHP Foundation, which will sponsor the design and development of PHP.

Installation and configuration

Example output of the phpinfo() function in PHP 7.1

There are two primary ways for adding support for PHP to a web server - as a native web server module, or as a CGI executable. PHP has a direct module interface called server application programming interface (SAPI), which is supported by many web servers including Apache HTTP Server, Microsoft IIS and iPlanet Web Server. Some other web servers, such as OmniHTTPd, support the Internet Server Application Programming Interface (ISAPI), which is Microsoft's web server module interface. If PHP has no module support for a web server, it can always be used as a Common Gateway Interface (CGI) or FastCGI processor; in that case, the web server is configured to use PHP's CGI executable to process all requests to PHP files.

PHP-FPM (FastCGI Process Manager) is an alternative FastCGI implementation for PHP, bundled with the official PHP distribution since version 5.3.3. When compared to the older FastCGI implementation, it contains some additional features, mostly useful for heavily loaded web servers.

When using PHP for command-line scripting, a PHP command-line interface (CLI) executable is needed. PHP supports a CLI server application programming interface (SAPI) since PHP 4.3.0. The main focus of this SAPI is developing shell applications using PHP. There are quite a few differences between the CLI SAPI and other SAPIs, although they do share many of the same behaviours.

PHP has a direct module interface called SAPI for different web servers; in case of PHP 5 and Apache 2.0 on Windows, it is provided in form of a DLL file called php5apache2.dll, which is a module that, among other functions, provides an interface between PHP and the web server, implemented in a form that the server understands. This form is what is known as a SAPI.

There are different kinds of SAPIs for various web server extensions. For example, in addition to those listed above, other SAPIs for the PHP language include the Common Gateway Interface and command-line interface.

PHP can also be used for writing desktop graphical user interface (GUI) applications, by using the PHP-GTK extension. PHP-GTK is not included in the official PHP distribution, and as an extension, it can be used only with PHP versions 5.1.0 and newer. The most common way of installing PHP-GTK is by compiling it from the source code.

When PHP is installed and used in cloud environments, software development kits (SDKs) are provided for using cloud-specific features. For example:

Numerous configuration options are supported, affecting both core PHP features and extensions. Configuration file php.ini is searched for in different locations, depending on the way PHP is used. The configuration file is split into various sections, while some of the configuration options can be also set within the web server configuration.

A broad overview of the LAMP software bundle, displayed here together with Squid

PHP is a general-purpose scripting language that is especially suited to server-side web development, in which case PHP generally runs on a web server. Any PHP code in a requested file is executed by the PHP runtime, usually to create dynamic web page content or dynamic images used on websites or elsewhere. It can also be used for command-line scripting and client-side graphical user interface (GUI) applications. PHP can be deployed on most web servers, many operating systems and platforms, and can be used with many relational database management systems (RDBMS). Most web hosting providers support PHP for use by their clients. It is available free of charge, and the PHP Group provides the complete source code for users to build, customize and extend for their own use.

Dynamic web page: example of server-side scripting (PHP and MySQL)

Originally designed to create dynamic web pages, PHP now focuses mainly on server-side scripting, and it is similar to other server-side scripting languages that provide dynamic content from a web server to a client, such as Microsoft's ASP.NET, Sun Microsystems' JavaServer Pages, and . PHP has also attracted the development of many software frameworks that provide building blocks and a design structure to promote rapid application development (RAD). Some of these include PRADO, CakePHP, Symfony, CodeIgniter, Laravel, Yii Framework, Phalcon and Laminas, offering features similar to other web frameworks.

The LAMP architecture has become popular in the web industry as a way of deploying web applications. PHP is commonly used as the P in this bundle alongside Linux, Apache and MySQL, although the P may also refer to Python, Perl, or some mix of the three. Similar packages, WAMP and MAMP, are also available for Windows and macOS, with the first letter standing for the respective operating system. Although both PHP and Apache are provided as part of the macOS base install, users of these packages seek a simpler installation mechanism that can be more easily kept up to date.

For specific and more advanced usage scenarios, PHP offers a well-defined and documented way for writing custom extensions in C or C++. Besides extending the language itself in form of additional libraries, extensions are providing a way for improving execution speed where it is critical and there is room for improvements by using a true compiled language. PHP also offers well-defined ways for embedding itself into other software projects. That way PHP can be easily used as an internal scripting language for another project, also providing tight interfacing with the project's specific internal data structures.

PHP received mixed reviews due to lacking support for multithreading at the core language level, though using threads is made possible by the "pthreads" PECL extension.

A command line interface, php-cli, and two ActiveX Windows Script Host scripting engines for PHP have been produced.

As of January 2013, PHP was used in more than 240 million websites (39% of those sampled) and was installed on 2.1 million web servers.

As of November 2023, PHP was used as the server-side programming language on 76.7% of websites, down from 83.5% previously, where the language could be determined, and PHP 7 is the most used version of the language with 61.4% of all websites on the web using that version.

In 2019, 11% of all vulnerabilities listed by the National Vulnerability Database were linked to PHP; historically, about 30% of all vulnerabilities listed since 1996 in this database are linked to PHP. Technical security flaws of the language itself or of its core libraries are not frequent (22 in 2009, about 1% of the total although PHP applies to about 20% of programs listed). Recognizing that programmers make mistakes, some languages include taint checking to automatically detect the lack of input validation which induces many issues. Such a feature is being developed for PHP, but its inclusion into a release has been rejected several times in the past.

There are advanced protection patches such as Suhosin and Hardening-Patch, specially designed for web hosting environments.

Historically, old versions of PHP had some configuration parameters and default values for such runtime settings that made some PHP applications prone to security issues. Among these, magic_quotes_gpc and register_globals configuration directives were the best known; the latter made any URL parameters become PHP variables, opening a path for serious security vulnerabilities by allowing an attacker to set the value of any uninitialized global variable and interfere with the execution of a PHP script. Support for " magic quotes" and "register globals" settings has been deprecated since PHP 5.3.0, and removed from PHP 5.4.0.

Another example for the potential runtime-settings vulnerability comes from failing to disable PHP execution (for example by using the engine configuration directive) for the directory where uploaded files are stored; enabling it can result in the execution of malicious code embedded within the uploaded files. The best practice is to either locate the image directory outside of the document root available to the web server and serve it via an intermediary script or disable PHP execution for the directory which stores the uploaded files.

Also, enabling the dynamic loading of PHP extensions (via enable_dl configuration directive) in a shared web hosting environment can lead to security issues.

Implied type conversions that result in different values being treated as equal, sometimes against the programmer's intent, can lead to security issues. For example, the result of the comparison is true, because strings that are parsable as numbers are converted to numbers; in this case, the first compared value is treated as scientific notation having the value (), which is zero. Errors like this resulted in authentication vulnerabilities in Simple Machines Forum, Typo3 and phpBB when MD5 password hashes were compared. The recommended way is to use hash_equals() (for timing attack safety), or the identity operator (===), as results in false.

In a 2013 analysis of over 170,000 website defacements, published by Zone-H, the most frequently (53%) used technique was the exploitation of file inclusion vulnerability, mostly related to insecure usage of the PHP language constructs include, require, and allow_url_fopen.

As of April 2021, W3Techs reports that 64% of websites using PHP, use versions 7.2 or older (which are no longer supported by The PHP Development Team) with 35% of all PHP websites using version 5.6 or older.

As of September 2021, Version 5 is still used by 24.5% of all websites. It is highly recommended to migrate to PHP version 7 or 8 and use random_int() instead of rand() or mt_rand(), as the latter functions are not cryptographically-secure. There are two attacks that can be performed over PHP entropy sources: "seed attack" and "state recovery attack". With current GPU technologies, an attacker can perform up to 2 ³⁰ MD5 calculations per second with a $250 GPU, while with an additional $500 can reach up to 2 ³² calculations. In combination with a " birthday attack" this can lead to serious security vulnerabilities.

# data[].attributes.attachment_link.title
Swift (lenguaje de programación) - Wikipedia, la enciclopedia libre

# data[].attributes.attachment_link.description
Swift es un lenguaje de programación multiparadigma creado por Apple enfocado en el desarrollo de aplicaciones para iOS y macOS. Fue presentado en WWDC 2014​ y está diseñado para integrarse con los Frameworks Cocoa y Cocoa Touch, puede usar cualquier biblioteca programada en Objective-C y llamar a funciones de C.

# data[].attributes.attachment_link.title
Tutorial Python 1: Introducción al Lenguaje de Programación

# data[].attributes.attachment_link.title
Java (lenguaje de programación) - Wikipedia, la enciclopedia libre

# data[].attributes.attachment_link.description
Java es un lenguaje de programación de propósito general, concurrente, orientado a objetos, que fue diseñado específicamente para tener tan pocas dependencias de implementación como fuera posible.