Строка запроса

Php передать параметр через ссылку

points to post below me.
When you’re doing the references with loops, you need to unset($var).

In reply to lars at riisgaardribe dot dk,

When a variable is copied, a reference is used internally until the copy is modified. Therefore you shouldn’t use references at all in your situation as it doesn’t save any memory usage and increases the chance of logic bugs, as you discoved.

I think a correction to my last post is in order.

When there is a constructor, the strange behavior mentioned in my last post doesn’t occur. My guess is that php was treating reftest() as a constructor (maybe because it was the first function?) and running it upon instantiation.

class reftest
public $a = 1 ;
public $c = 1 ;

public function __construct ()
return 0 ;
>

$reference -> reftest ();
$reference -> reftest2 ();

echo $reference -> a ; //Echoes 2.
echo $reference -> c ; //Echoes 2.
?>

In this example class name is different from its first function and however there is no construction function. In the end as you guess «a» and «c» are equal. So if there is no construction function at same time class and its first function names are the same, «a» and «c» doesn’t equal forever. In my opinion php doesn’t seek any function for the construction as long as their names differ from each others.

class reftest_new
<
public $a = 1 ;
public $c = 1 ;

$reference = new reftest_new ();

$reference -> reftest ();
$reference -> reftest2 ();

echo $reference -> a ; //Echoes 2.
echo $reference -> c ; //Echoes 2.
?>

It matters if you are playing with a reference or with a value

Here we are working with values so working on a reference updates original variable too;

$b++;
echo «$a, $b»;//Output: 2, 2 both values are updated

$b = 10;
echo «$a, $b»;//Output: 10, 10 both values are updated

$b =$c; //This assigns value 2 to $b which also updates $a
echo «$a, $b»;//Output: 22, 22

But, if instead of $b=$c you do
$b = &$c; //Only value of $b is updated, $a still points to 10, $b serves now reference to variable $c

The order in which you reference your variables matters.

echo $a1 ; //Echoes «One»
echo $b1 ; //Echoes «One»

echo $a2 ; //Echoes «Four»
echo $b2 ; //Echoes «Four»
?>

If you set a variable before passing it to a function that takes a variable as a reference, it is much harder (if not impossible) to edit the variable within the function.

foo ( $unset );
echo( $unset );
foo ( $set = «set\n» );
echo( $set );

It baffles me, but there you have it.

In reply to Drewseph using foo($a = ‘set’); where $a is a reference formal parameter.

$a = ‘set’ is an expression. Expressions cannot be passed by reference, don’t you just hate that, I do. If you turn on error reporting for E_NOTICE, you will be told about it.

Resolution: $a = ‘set’; foo($a); this does what you want.

Here’s a good little example of referencing. It was the best way for me to understand, hopefully it can help others.

When using references in a class, you can reference $this-> variables.

class reftest
public $a = 1 ;
public $c = 1 ;

$reference -> reftest ();
$reference -> reftest2 ();

echo $reference -> a ; //Echoes 2.
echo $reference -> c ; //Echoes 2.
?>

However, this doesn’t appear to be completely trustworthy. In some cases, it can act strangely.

class reftest
public $a = 1 ;
public $c = 1 ;

$reference -> reftest ();
$reference -> reftest2 ();

echo $reference -> a ; //Echoes 3.
echo $reference -> c ; //Echoes 2.
?>

In this second code block, I’ve changed reftest() so that $b increments instead of just gets changed to 2. Somehow, it winds up equaling 3 instead of 2 as it should.

I discovered something today using references in a foreach

echo $a1 [ ‘a’ ]; // will echo b (!)
?>

After reading the manual this looks like it is meant to happen. But it confused me for a few days!

(The solution I used was to turn the second foreach into a reference too)

An interesting if offbeat use for references: Creating an array with an arbitrary number of dimensions.

For example, a function that takes the result set from a database and produces a multidimensional array keyed according to one (or more) columns, which might be useful if you want your result set to be accessible in a hierarchial manner, or even if you just want your results keyed by the values of each row’s primary/unique key fields.

function array_key_by ( $data , $keys , $dupl = false )
/*
* $data — Multidimensional array to be keyed
* $keys — List containing the index/key(s) to use.
* $dupl — How to handle rows containing the same values. TRUE stores it as an Array, FALSE overwrites the previous row.
*
* Returns a multidimensional array indexed by $keys, or NULL if error.
* The number of dimensions is equal to the number of $keys provided (+1 if $dupl=TRUE).
*/
// Sanity check
if (! is_array ( $data )) return null ;

// Allow passing single key as a scalar
if ( is_string ( $keys ) or is_integer ( $keys )) $keys = Array( $keys );
elseif (! is_array ( $keys )) return null ;

// Our output array
$out = Array();

// Loop through each row of our input $data
foreach( $data as $cx => $row ) if ( is_array ( $row ))

// Loop through our $keys
foreach( $keys as $key )
$value = $row [ $key ];

if (!isset( $last )) // First $key only
if (!isset( $out [ $value ])) $out [ $value ] = Array();
$last =& $out ; // Bind $last to $out
>
else // Second and subsequent $key.
if (!isset( $last [ $value ])) $last [ $value ] = Array();
>

if (isset( $last ))
// At this point, copy the $row into our output array
if ( $dupl ) $last [ $cx ] = $row ; // Keep previous
else $last = $row ; // Overwrite previous
>
unset( $last ); // Break the reference
>
else return NULL ;

// A sample result set to test the function with
$data = Array(Array( ‘name’ => ‘row 1’ , ‘foo’ => ‘foo_a’ , ‘bar’ => ‘bar_a’ , ‘baz’ => ‘baz_a’ ),
Array( ‘name’ => ‘row 2’ , ‘foo’ => ‘foo_a’ , ‘bar’ => ‘bar_a’ , ‘baz’ => ‘baz_b’ ),
Array( ‘name’ => ‘row 3’ , ‘foo’ => ‘foo_a’ , ‘bar’ => ‘bar_b’ , ‘baz’ => ‘baz_c’ ),
Array( ‘name’ => ‘row 4’ , ‘foo’ => ‘foo_b’ , ‘bar’ => ‘bar_c’ , ‘baz’ => ‘baz_d’ )
);

// First, let’s key it by one column (result: two-dimensional array)
print_r ( array_key_by ( $data , ‘baz’ ));

// Or, key it by two columns (result: 3-dimensional array)
print_r ( array_key_by ( $data , Array( ‘baz’ , ‘bar’ )));

// We could also key it by three columns (result: 4-dimensional array)
print_r ( array_key_by ( $data , Array( ‘baz’ , ‘bar’ , ‘foo’ )));

Источник

Php передать параметр через ссылку

To experiment on performance of pass-by-reference and pass-by-value, I used this script. Conclusions are below.

#!/usr/bin/php
function sum ( $array , $max ) < //For Reference, use: "&$array"
$sum = 0 ;
for ( $i = 0 ; $i < 2 ; $i ++)#$array[$i]++; //Uncomment this line to modify the array within the function.
$sum += $array [ $i ];
>
return ( $sum );
>

$max = 1E7 //10 M data points.
$data = range ( 0 , $max , 1 );

$start = microtime ( true );
for ( $x = 0 ; $x < 100 ; $x ++)$sum = sum ( $data , $max );
>
$end = microtime ( true );
echo «Time: » .( $end — $start ). » s\n» ;

/* Run times:
# PASS BY MODIFIED? Time
— ——- ——— —-
1 value no 56 us
2 reference no 58 us

3 valuue yes 129 s
4 reference yes 66 us

1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
only copied on write. That’s why #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
[You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]

2. You do use &$array to tell the compiler «it is OK for the function to over-write my argument in place, I don’t need the original
any more.» This can make a huge difference to performance when we have large amounts of memory to copy.
(This is the only way it is done in C, arrays are always passed as pointers)

3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
(This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
in an array)

5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn’t allow it, but it
would be meaningful for the caller to decide to pass data in as a reference. i.e. «I’m done with the variable, it’s OK to stomp
on it in memory».
*/
?>

Источник

Php передать параметр через ссылку

Ссылки в PHP позволяют ссылаться на область памяти, где расположено значение переменной или параметра. Для создания ссылки перед переменной указывается символ амперсанда — & . Но перед рассмотрением ссылок сначала рассмотрим простой пример копирования переменных:

"; // tom = Tom echo "sam = $sam"; // sam = Sam ?>

Здесь переменной $sam присваивается значение переменной $tom («Tom»). Затем той же переменной $sam присваивается новое значение — «Sam». Результат программы ожидаем — обе переменные имеют различные значения:

Теперь при копировании значения переменных передадим ссылку:

"; // tom = Sam echo "sam = $sam"; // sam = Sam ?>

Здесь нас интересует выражение

В данном случае переменной $sam передается не копия значения переменной $tom , как в предыдущем случае, а ссылка на область в памяти, которую занимает переменная $tom . То есть после выполнения инструкции

Обе переменных будут указывать на один и тот же адрес в памяти. Это приведет к тому, что изменение значения одной из этих переменных приведет к изменению значения другой переменной. Потому что они ссылаются на один и тот же участок в памяти и соответственно имеют одно общее значение:

Присвоить ссылку на переменную можно двумя способами:

Передача по ссылке

В примере в прошлых темах мы передавали параметры по значению . Но в PHP есть и другая форма передачи параметров — по ссылке . Рассмотрим два этих способа передачи параметров и сравним. Стандартная передача параметра по значению:

 $number = 5; square($number); echo "
number = $number"; ?>

В данном случае внутри функции square() значение параметра $a возводится в квадрат. То есть значение параметра внутри функции изменяется. Однако после вызова функции square() значение переменной $number , которое передается параметру $a, не изменится. Это и есть передача по значению, она никак не затрагивает переменную $number .

Теперь рассмотрим передачу параметра по ссылке:

 $number = 5; square($number); echo "
number = $number"; ?>

При передаче по ссылке перед параметром ставится знак амперсанда: function square(&$a) . Теперь интерпретатор будет передавать не значение переменной, а ссылку на эту переменную в памяти. То есть теперь и переменная $number и параметр $a будут указывать на одну и ту же область в памяти. В итоге, значение переменной $number после передачи параметру &$a также будет изменено.

Возвращение ссылки из функции

Функция также может возвращать ссылку. В этом случае при определении и вызове функции перед ее именем ставится знак амперсанда:

 $userName = "admin"; $checkedName = &checkName($userName); echo "
userName: $userName"; echo "
checkedName: $checkedName"; ?>

В данном случае функция checkName() получает параметр по ссылке и возвращает ссылку — фактически ссылку, которая передается в функции. Для этого перед определением функции указан символ амперсанда:

Для имитации работы функция проверяет имя пользователя и изменяет его на некоторое стандартное, если оно равно «admin».

При вызове функции перед ее именем указывается символ амерсанда:

После выполнения функции переменная $checkedName фактически будет содержать ссылку на переменную $userName .

Источник

Урок 10: Передача переменных через URL

При работе с PHP часто необходимо передать переменные с одной страницы в другую. Этот урок — о передаче переменных в URL.

Как это работает?

Возможно, вас удивляло, почему некоторые URL выглядят наподобие этого:

Почему после имени страницы стоит знак вопроса?

Ответ: символы после знака вопроса это строка HTTP-запроса. Строка HTTP-запроса может содержать как имена переменных, так и их значения. В вышеприведённом примере строка HTTP-запроса содержит переменную «id» со значением «1254».

http://html.net/page.php?name=Joe

То есть у вас снова переменная («name») со значением («Joe»).

Как получить переменную с помощью PHP?

Предположим, у вас есть PHP-страница people.php. Можно вызвать её с использованием URL:

В PHP вы можете получить значение переменной ‘name’ таким образом:

документация

То есть вы используете $_GET для поиска значения именованной переменной. Попробуем на примере:

     // Значение переменной найдено echo "

Hello " . $_GET["name"] . "

";
?>

Попробуйте в этом примере заменить «Joe» вашим собственным в URL и снова вызвать документ! Довольно прикольно, а?

Несколько переменных в одном URL

В URL можно передавать и не одну переменную. Разделяя переменные знаком &, можно передавать несколько:

Этот URL содержит две переменные: name и age. Как и ранее, можно получит переменные так :

Добавим в пример ещё одну переменную:

     // Значение имени переменной name найдено echo "

Hello " . $_GET["name"] . "

";
// Значение имени переменной age найдено echo "

You are " . $_GET["age"] . " years old

";
?>

Вы узнали, как передать значения между страницами с использованием URL. В следующем уроке мы изучим другой способ: формы.

Источник

Читайте также:  Coding with java pdf
Оцените статью