MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

Retorno por Referencia

Devolver por Referencia es muy útil cuando se quiere utilizar una función para averiguar a que variable debe estar una referencia ligada. Cuando se devuelve por referencia, se debe utilizar esta sintáxis:

function &encontrar_var ($param)
{
   ...codigo...
   return $var_encontrada;
}

$foo =& encontrar_var ($bar);
$foo->x = 2;

En este ejemplo, el atributo del objeto devuelto por la función encontrar_var fue asignado, no ya en la copia, como habría sucedido si no se utilizaba la sintáxis de referencias.

Nota: A diferencia del paso de parámetros, aquí se debe utilizar & en ambos lugares - para indicar que se pretende devolver por referencia ( y no una copia, como usualmente sucede) y que además esa referencia sea 'ligada' a una variable, y no solo asignada.



add a note add a note User Contributed Notes
Retorno por Referencia
neozenkai at yahoo dot com
15-Jul-2006 01:38
While trying to create a function to return Database connection objects, it took me a while to get this right:

<?php

class TestClass
{
   var
$thisVar = 0;

   function
TestClass($value)
   {
      
$this->thisVar = $value;
   }

   function &
getTestClass($value)
   {
       static
$classes;

       if (!isset(
$classes[$value]))
       {
          
$classes[$value] = new TestClass($value);
       }

       return
$classes[$value];
   }
}

echo
"<pre>";

echo
"Getting class1 with a value of 432\n";
$class1 =& TestClass::getTestClass(432);
echo
"Value is: " . $class1->thisVar . "\n";

echo
"Getting class2 with a value of 342\n";
$class2 =& TestClass::getTestClass(342);
echo
"Value is: " . $class2->thisVar . "\n";

echo
"Getting class3 with the same value of 432\n";
$class3 =& TestClass::getTestClass(432);
echo
"Value is: " . $class3->thisVar . "\n";

echo
"Changing the value of class1 to 3425, which should also change class3\n";
$class1->thisVar = 3425;

echo
"Now checking value of class3: " . $class3->thisVar . "\n";

?>

Which outputs:

Getting class1 with a value of 432
Value is: 432
Getting class2 with a value of 342
Value is: 342
Getting class3 with the same value of 432
Value is: 432
Changing the value of class1 to 3425, which should also change class3
Now checking value of class3: 3425

Note that PHP syntax is different from C/C++ in that you must use the & operator in BOTH places, as stated by the manual. It took me a while to figure this out.
rwruck
27-Feb-2006 09:22
The note about using parentheses when returning references is only true if the variable you try to return does not already contain a reference.

<?php
// Will return a reference
function& getref1()
  {
 
$ref =& $GLOBALS['somevar'];
  return (
$ref);
  }

// Will return a value (and emit a notice)
function& getref2()
  {
 
$ref = 42;
  return (
$ref);
  }

// Will return a reference
function& getref3()
  {
  static
$ref = 42;
  return (
$ref);
  }
?>
warhog at warhog dot net
13-Dec-2005 12:04
firstly a note on the post below: technically correct that -> "to get a reference to an exsisting class and it's properties" should be "...to an existing object..."

in PHP5 it's senseless to return objects by reference.. let's say you have, as in the post below, a class which should return a reference to its own instance (maybe it's been created using the singleton pattern..), than it's no problem to simply return that variable holding the instance.
In PHP5 variables holding objects are always references to a specific object, so when you return (=copy) a variable "having" an object you in fact return a reference to that object.

Because of that behaviour, which is very common for many programming languages, especially those, which are to be compiled (due to memory problems and so on), you have to use the clone-function which was introduced in PHP5.

Here an example to underline what i mean:

<?php

class sample_singleton
{
  protected static
$instance = NULL;
 
  private function
__construct()
  { }

  public static function
create()
  {
self::$instance = new sample_singleton(); }

  public static function
getInstance()
  { return
self::$instance; }

  public function
yea()
  { echo
"wuow"; }
}

sample_singleton::create();

// $singleton will be a reference to sample_singleton::$instance
$singleton = sample_singleton::getInstance();

$singleton->yea();

?>

Note some more (maybe) strange behaviour: although $instance is private you can have a reference pointing on it. Maybe that does not seem strange to you in any way, but maybe you wondered as i did : )

The code posted here was just a sample to illustrate my posting, for using the singleton pattern please look it up in the manual. I just used this cause it was the simplest example which went in my mind right know.
willem at designhulp dot nl
09-Oct-2005 04:54
There is an important difference between php5 and php4 with references.

Lets say you have a class with a method called 'get_instance' to get a reference to an exsisting class and it's properties.

<?php
class mysql {
   function
get_instance(){
      
// check if object exsists
      
if(empty($_ENV['instances']['mysql'])){
          
// no object yet, create an object
          
$_ENV['instances']['mysql'] = new mysql;
       }
      
// return reference to object
      
$ref = &$_ENV['instances']['mysql'];
       return
$ref;
   }
}
?>

Now to get the exsisting object you can use
mysql::get_instance();

Though this works in php4 and in php5, but in php4 all data will be lost as if it is a new object while in php5 all properties in the object remain.
obscvresovl at NOSPAM dot hotmail dot com
24-Dec-2004 01:09
An example of returning references:

<?

$var
= 1;
$num = NULL;

function &
blah()
{
  
$var =& $GLOBALS["var"]; # the same as global $var;
  
$var++;
   return
$var;
}

$num = &blah();

echo
$num; # 2

blah();

echo
$num; # 3

?>

Note: if you take the & off from the function, the second echo will be 2, because without & the var $num contains its returning value and not its returning reference.
hawcue at yahoo dot com
16-Mar-2004 07:58
Be careful when using tinary operation condition?value1:value2

See the following code:

$a=1;
function &foo()
{
  global $a;
  return isset($a)?$a:null;
}
$b=&foo();
echo $b;  // shows 1
$b=2;
echo $a;  // shows 1 (not 2! because $b got a copy of $a)

To let $b be a reference to $a, use "if..then.." in the function.
contact at infopol dot fr
12-Feb-2004 09:36
A note about returning references embedded in non-reference arrays :

<?
$foo
;

function
bar () {
   global
$foo;
  
$return = array();
  
$return[] =& $foo;
   return
$return;
}

$foo = 1;
$foobar = bar();
$foobar[0] = 2;
echo
$foo;
?>

results in "2" because the reference is copied (pretty neat).
zayfod at yahoo dot com
03-Dec-2003 09:23
There is a small exception to the note on this page of the documentation. You do not have to use & to indicate that reference binding should be done when you assign to a value passed by reference the result of a function which returns by reference.

Consider the following two exaples:

<?php

function    & func_b ()
{
  
$some_var = 2;
   return
$some_var;
}

function   
func_a (& $param)
{
  
# $param is 1 here
  
$param = & func_b();
  
# $param is 2 here
}

$var = 1;
func_a($var);
# $var is still 1 here!!!

?>

The second example works as intended:

<?php

function    & func_b ()
{
  
$some_var = 2;
   return
$some_var;
}

function   
func_a (& $param)
{
  
# $param is 1 here
  
$param = func_b();
  
# $param is 2 here
}

$var = 1;
func_a($var);
# $var is 2 here as intended

?>

(Experienced with PHP 4.3.0)

Citas célebres

La belleza es la llave de los corazones; la coquetería es la ganzúa.

P. Masson
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_002.jpg
Contenidos Web

Chiste de... Camareros
A todo tren

Restaurante de lujo:

- Que tomarán los señores....

- A mi me pone una langosta Thermidor y un cava Juve & Camps reserva de familia.

- Excelente decisión! Y a su señora....

- Póngale un fax y dígale que me lo estoy pasando de lujo.
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_035.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake Mania
Jugadores: 6835
Categoría del juego: Acción
Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero.
Rainbow WebRainbow Web
Jugadores: 2199
Categoría del juego: Puzzles
Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente.
Mahjongg FortunaMahjongg Fortuna
Jugadores: 12462
Categoría del juego: Solitarios
Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta.
Chainz 2Chainz 2
Jugadores: 6955
Categoría del juego: Puzzles
Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más.
DeliciousDelicious
Jugadores: 4405
Categoría del juego: Acción
Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues!
BookwormBookworm
Jugadores: 4568
Categoría del juego: Palabras
Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos!
ZumaZuma
Jugadores: 4976
Categoría del juego: Acción
Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás!
Jewel of AtlantisJewel of Atlantis
Jugadores: 3798
Categoría del juego: Puzzles
Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis.
Jewel QuestJewel Quest
Jugadores: 3727
Categoría del juego: Puzzles
Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos!
Bejeweled 2Bejeweled 2
Jugadores: 3659
Categoría del juego: Puzzles
Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0426.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail

Warning: array_rand(): First argument has to be an array in /var/www/html/contenidos/efemerides.php on line 14
Sucedió el...

31 de agosto de

Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid