This site uses cookies.
Some of these cookies are essential to the operation of the site,
while others help to improve your experience by providing insights into how the site is being used.
For more information, please see the ProZ.com privacy policy.
VIA AILooking for an interpreter?
Remoto by ProZ.com connects you with an identity-verified interpreter by video or phone in about 60 seconds — 300+ languages, on demand or booked ahead.
Try Remoto »
Working languages:
English to Spanish
Client-vendor relationship recorded successfully!
berthaferrer has been added to your list of hired vendors.
This person has a SecurePRO™ card. Because this person is not a ProZ.com Plus subscriber, to view his or her SecurePRO™ card you must be a ProZ.com Business member or Plus subscriber.
Affiliations
This person is not affiliated with any business or Blue Board record at ProZ.com.
Rates per language pair: English to Spanish - Rates: 0.05 - 0.10 USD per word / 20 - 40 USD per hour
Blue Board entries made by this user
0 entries
Payment methods accepted
Wire transfer
Portfolio
Sample translations submitted: 1
English to Spanish: Zend PHP 5 Certification Study Guide General field: Tech/Engineering Detailed field: Computers: Software
Source text - English PHP | Arquitect´s Zend PHP 5 Certification Study Guide
By Davey Shafik with Ben Ramsay
Chapter 6
Object Oriented Programming in PHP
Object orientation is probably the area that has been subject to the most significant and far-reaching changes with the advent of PHP 5. Rather than making things incompatible with previous versions of the language, however, they enhance PHP 4’s meagre OOP offerings and make PHP 5 a fully functional object-oriented language — plus, of course, they make your life easier.
OOP Fundamentals
While the goal of this chapter is not to provide a guide to the concepts of objectoriented programming, it’s a good idea to take a quick look at some of the fundamentals.
OOP revolves around the concept of grouping code and data together in logical units called classes. This process is usually referred to as encapsulation, or information hiding, since its goal is that of dividing an application into separate entities whose internal components can change without altering their external interfaces.
Thus, classes are essentially a representation of a set of functions (also called methods) and variables (called properties) designed to work together and to provide a specific interface to the outside world. It is important to understand that classes are just blueprints that cannot be used directly—they must be instantiated into objects, which can then interact with the rest of the application. You can think of classes as the blueprints for building a car, while objects are, in fact, the cars themselves as they come out of the production line. Just like a single set of blueprints can be used to produce an arbitrary number of cars, an individual class can normally be instantiated into an arbitrary number of objects.
Declaring a Class
The basic declaration of a class is very simple:
class myClass {
// Class contents go here
}
As you have probably guessed, this advises the PHP interpreter that you are declaring a class called myClass whose contents will normally be a combination of constants, variables and functions (called methods).
Instantiating an Object
Once you have declared a class, you need to instantiate it in order to take advantage of the functionality it offers. This is done by using the new construct:
$myClassInstance = new myClass();
In PHP 5, objects are treated differently from other types of variables. An object is always passed by reference (in reality, it is passed by handle, but for all practical purposes there is no difference), rather than by value. For example:
$myClassInstance = new myClass();
$copyInstance = $myClassInstance();
In this case, both $myInstance and $copyInstance will point to the same object, even though we didn’t specify that we wanted this to happen by means of any special syntax. This is the standard behaviour of objects in most languages, but wasn’t the case in PHP 4, where objects were handled like any other normal variables and were, therefore, passed by value.
Class Inheritance
One of the key fundamental concepts of OOP is inheritance. This allows a class to extend another class, essentially adding new methods and properties, as well as overriding existing ones as needed. For example:
class a {
function test()
{
echo "a::test called";
}
function func()
{
echo "a::func called";
}
}
class b extends a {
function test()
{
echo "b::test called";
}
}
class c extends b {
function test()
{
parent::test();
}
}
class d extends c {
function test()
{
b::test();
}
}
$a = new a();
$b = new b();
$c = new c();
$d = new d();
In this script, we start by declaring a class called a. We then declare the class b, which extends a. As you can see, this class also has a test() method, which overrides the one declared in a, thus outputting b::test called. Note, however, that we can still access a’s other methods—so that calling $b->func() effectively executes the function in the a class.
Naturally, extending objects in this fashion would be very limiting, since you would only be able to override the functionality provided by parent classes, without any opportunity for reuse (unless you implement your methods using different names). Luckily, parent classes can be accessed using the special parent::namespace, as we did for class c above; you can also access any other ancestor classes by addressing their methods by name—like we did, for example, in class d.
Constructors
PHP 5 introduces the concept of the unified constructor and, along with it, a new destructor for objects. The constructor and destructor are special classmethods that are called, as their names suggest, on object creation and destruction, respectively.
Constructors are useful for initializing an object’s properties, or for performing startup procedures, such as, for example, connecting to a database, or opening a remote file.
The concept of the constructor is, of course, not new to PHP 5. In PHP 4, it was
possible to define a class method whose name was the same as the class itself; PHP would then consider this method to be the class’ constructor and call it whenever a new instance of the class was created. This approach had several drawbacks—for example, if you decided to rename your class, you would also have to rename your constructor.
To avoid these problems, PHP 5 now uses the magic __construct() method as the constructor for any class regardless of the class’ name. This greatly simplify things, and provides you with a standard mechanismto recognize and call constructors in a consistent manner:
class foo {
function __construct()
{
echo __METHOD__;
}
function foo()
{
// PHP 4 style constructor
}
}
new foo();
This example will display foo::__construct (the __METHOD__ constant is replaced at compilation time with the name of the current class method). Note that, if the __construct() method is not found, PHP will look for the old PHP 4-style constructor (foo) and call that instead.
Translation - Spanish Guía de estudio para la Certificación Zend PHP 5.
Autores: Davey Shafik with Ben Ramsay
Capítulo 6. Programación Orientada a Objetos en PHP.
La Orientación a Objetos es probablemente el área que ha sido objeto de los cambios más significativos y de gran alcance con la llegada de PHP 5. En lugar de hacer las cosas incompatibles con las versiones anteriores del lenguaje, mejoraron las escasas ofertas de PHP 4 en POO y hacen a PHP 5 un lenguaje orientado a objeto totalmente funcional – además, por supuesto, que hacen tu vida más fácil.
Fundamentos de la Programación Orientada a Objetos
Si bien el objetivo de este capítulo no es proveer una guía de los conceptos de programación orientada a objetos, es una buena idea dar un rápido vistazo a algunos de los fundamentos.
La POO gira en torno al concepto de agrupación de código y dato en unidades lógicas denominadas clases. Este proceso es generalmente referido como encapsulamiento, o ocultamiento de información, ya que su fin es la de dividir una aplicación en entidades separadas cuyos componentes internos pueden cambiar sin alterar sus interfaces externas.
Por lo tanto, las clases son esencialmente una representación de un conjunto de funciones (también llamados métodos) y variables (llamadas propiedades) diseñados para trabajar juntos y para ofrecer una interfaz con el mundo exterior. Es importante entender que las clases son sólo blueprints (planos de diseño) que no pueden ser utilizadas directamente – ellas deben ser instanciadas en objetos, los cuales pueden entonces interactuar con el resto de la aplicación. Puedes pensar que las clases son como los planos de diseño para construir un carro, mientras que los objetos son, de hecho, los carros que salen de la línea de producción. Al igual que un único conjunto de planos de diseño puede ser utilizado para producir un número arbitrario de carros, una clase individual puede normalmente ser instanciada en un número arbitrario de objetos.
Declarando una Clase
La declaración básica de una clase es muy simple:
class miClase{
// El contenido de la clase va aquí
}
Como ustedes probablemente han adivinado, esto advierte al intérprete de PHP que tú estás declarando una clase llamada miClase cuyo contenido será normalmente una combinación de constantes, variables y funciones (llamadas métodos).
Instanciando un Objeto
Una vez que has declarado una clase, necesitas instanciarla con el fin de aprovechar la funcionalidad que ella ofrece. Esto se hace mediante el uso del constructor new:
$miClaseInstancia = new miClase();
En PHP 5, los objetos se tratan de manera diferente a los otros tipos de variables. Un objeto es siempre pasado por referencia (en realidad, es pasado por un manejador, pero para los efectos no hay diferencia), en vez de por valor. Por ejemplo:
$miClaseInstancia = new mi Clase();
$copiaInstancia = $miClaseInstancia();
En este caso, ambas variables $miClaseInstancia y $copiaInstancia apuntarán al mismo objeto, a pesar de que nosotros no especificamos que queríamos que esto ocurriese por medio de ninguna sintaxis especial. Este es el comportamiento estándar de los objetos en la mayoría de los lenguajes, pero no era el caso de PHP 4, donde los objetos eran manejados como cualquier otra variable, y eran, por lo tanto, pasados por valor.
Herencia de las Clases
Uno de los conceptos fundamentales de la POO es la herencia. Esto permite a una clase extender a otra clase, esencialmente agregando nuevos métodos y propiedades, así como sobrescribiendo, cuando sea necesario, los que ya existen.
clase a {
function prueba()
{
echo “a::prueba llamada”;
}
function func()
{
echo “a::func llamada”;
}
}
class b extends a{
function prueba()
{
echo “b::prueba llamada”;
}
}
class c extends b {
function prueba()
{
parent::prueba();
}
}
class d extends c{
function prueba()
{
b::prueba();
}
}
En este código, empezamos por declarar una clase llamada a. A continuación, declaramos la clase b, la cual extiende a a. Como se puede observar, esta clase también tiene un método llamado prueba(), el cual sobrescribe el declarado en a, por lo tanto la salida es b::prueba llamada. Nota, sin embargo, que nosotros aún podemos acceder a los otros métodos de a – de modo que al llamar $b->func() efectivamente ejecuta la función declarada en la clase a.
Naturalmente, extender los objetos de esta forma sería muy limitante, ya que sólo serías capaz de sobrescribir la funcionalidad proporcionada por las clases padres, sin ninguna oportunidad para la reutilización (a menos que implementes los métodos usando nombres diferentes). Por suerte, las clases padres pueden ser accedidas usando el namespace especial llamado parent::, así como hicimos en la clase c mostrada arriba; también puedes acceder a cualquier otra clase ancestro utilizando los métodos por sus nombres – así como hicimos, por ejemplo, en la clase d.
Constructores
PHP 5 introduce el concepto de constructor unificado y, junto con él, un nuevo destructor de objetos. El constructor y destructor son métodos de clases especiales que son llamados, como sus nombres sugieren, al crear y destruir un objeto, respectivamente.
Los constructores son útiles para la inicialización de las propiedades de un objeto, o para la ejecución de procedimientos de inicio, tales como, por ejemplo, conectarse a una base de datos o abrir un archivo remoto.
El concepto de constructor es, por supuesto, no nuevo en PHP 5. En PHPP 4, era posible definir un método de una clase cuyo nombre era igual al nombre de la clase misma.; PHP entonces consideraría este método como el constructor de la clase y lo llamaría siempre que una nueva instancia de la clase fuese creada. Este enfoque tenía muchos inconvenientes – por ejemplo, si decidías renombrar tu clase, también tendrías que renombrar tu constructor.
Para evitar estos problemas, PHP 5 ahora utiliza el mágico método __construct() como el constructor de cualquier clase independientemente del nombre de la clase. Esto simplifica las cosas enormemente, y te proporciona un mecanismo estándar para reconocer y llamar constructores de manera consistente:
class foo {
function _ _ construct()
{
echo _ _ method _ _ ;
}
function foo()
{
// estido de constructor de PHP 4
}
}
new foo();
Este ejemplo mostrará foo::__construct (la constante __METHOD__ es reemplazada en tiempo de compilación por el nombre del método de la clase). Nota que, si el método __construct() no es encontrado (not found), PHP buscará el constructor viejo al estilo PHP 4 (foo) y llamará a éste en cambio.
More
Less
Experience
Years of experience: 20. Registered at ProZ.com: Jul 2009.
A disciplined and organized professional able to relate to people from a wide variety of backgrounds and nationalities. Team player but able to work on own initiative, self-motivated with good work ethic.
English to Spanish freelance translator with 1 years experience, specializing in IT and technical translations. Native Latin American Spanish speaker.
Qualified IT professional with 9 years experience in computer networks, software, hardware, programming and general IT environment.
Keywords: IT, computers, software, hardware, networks, database, programming, web site design, certifications, manuals. See more.IT, computers, software, hardware, networks, database, programming, web site design, certifications, manuals, technology, spanish, translation, south american, latin, subtitles. See less.