Ссылка на выполнение php

Ссылка на выполнение 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-функцию нажатием на ссылку

Как запустить PHP-функцию нажатием на ссылку

Очень часто бывает нужно запустить PHP-функцию нажатием на ссылку, например, нажать на ссылку «Удалить» рядом с фотографией, после этого запускается PHP-функция, которая её удалит, и сразу же идёт возврат на страницу. Вот как реализовать подобную задачу, я и покажу в этой статье.

Разберём простой пример запуска PHP-функции нажатием на ссылку с целью изменения размера шрифта:

Внутри IF мы можем выполнить любой PHP-код, в том числе, и вызвать любую функцию. Что касается данного примера, то мы здесь используем ещё и сессию. Это для того, чтобы при переходе на другие страницы, нам не надо было тащить GET-параметр size за собой, и в то же время, чтобы выбранный пользователем размер шрифта сохранялся.

Вот таким простым образом можно вызывать PHP-код нажатием по HTML-ссылке.

Создано 31.10.2012 10:01:33

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 2 ):

    Михаил,а как здесь можно добавить прокрутку ссылок,prev и next?? Например я вывел ссылки с помощью цикла, а рядом установить prev и next.Или может есть материал по перемоткам ??

    Здравствуйте, shamil. После вывода ваших ссылок на страницу или в блок, сделайте пагинацию и просто разбейте на нужное количество ссылок на странице\блоке. Как реализовать пагинацию? Статья есть на нашем сайте: http://myrusakov.ru/php-pagination.html

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Как передать ссылку на метод?

    Подскажите, можно ли в. PHP передать ссылку на метод объекта как аргумент в функции?

    class Converter < public function convertDate($date) < . >> function convert($rawData, callable $convertMethod) < return $convertMethod($rawData); >// Использование $converter = new Converter; $data = convert($rawData, $converter::convertDate)

    Простой 1 комментарий

    FanatPHP

    $data = convert($rawData, [$converter,'convertDate']);
    class cat < function say() < echo 'meow' . PHP_EOL; >> class dog < function say() < echo 'woof' . PHP_EOL; >> call_user_func([dog, 'say']); call_user_func(dog . '::say'); $cat = new cat(); call_user_func([$cat, 'say']);

    FanatPHP

    call_user_func устарела, сейчас проще писать [new dog, ‘say’]();

    и кстати забавно что на ideone отключены deprecated ошибки

    FanatPHP

    Так что ты бы подправил код, а то неудобно получается. человек пришел с вопросом как задачу решить, а ты ему ворох ошибок, да еще и фатальных 🙂

    FanatPHP

    Кстати, mitaichik а зачем ты пометил этот ответ решением если у тебя не было вопроса, как вызвать, а вопрос был как передать?

    mitaichik

    FanatPHP

    mitaichik, WUT? в каком месте там показаны «варианты передачи ссылки»?
    Ответ про ненужную тебе функцию call_user_func, поскольку код вызова у тебя уже и так есть, причем почти в каждом варианте ошибки, от нотисов до фатальных.

    Единственный рабочий вариант — последний, но при этом зачем-то приплетена функция call_user_func

    Источник

    Читайте также:  pre
    Оцените статью