Рекомендации на будущее с системой голосования. Как пропустить необязательные аргументы в вызове функции

> Php функции > Php скрипты func_get_arg func_get_arg -- Возвращает элемент из списка аргументов Описаниеmixed func_get_arg ( int arg_num)

Возвращает arg_num -ый аргумент из списка аргументов пользовательской функции. Нумерация аргументов функции начинается с нуля. func_get_arg() генерирует предупреждение при вызове вне определения функции.

Если arg_num больше количества переданных аргументов, будет сгенерировано предупреждение и func_get_arg() вернет FALSE .

func_get_arg() может быть использована совместно с func_num_args() и func_get_args() для создания функций с переменным количеством аргументов.

User Contributed Notesbishop
11-Dec-2004 08:58

Regarding a "deferment" operator for dvogel at ssc dot wisc dot edu, pick your poison:


mw atto lanfear dotto com
08-Dec-2004 01:56

func_get_arg () does not appear to be allowed to be used as a function argument itself within class constructors in PHP 5.0.2 (wonk-ay!!!):

And "extract" the array inside the all.php?act=funct&argument= you don"t need to do tricks like type-checking for parameter-recognition, in this case.
04-Jun-2004 05:16

I actually think that there is need for such "do absolutely everything" functions. I use them mostly as tools for rapid prototyping.
And there is a method with which you may be able to pass several strings to a function: ereg ();
Another use for such functions is to create little code snippets for other people out there. They won"t have to edit the function any longer if they do not use a parameter. They just don"t name it when calling the all.php?act=funct&argument=
This results in allrounder functions that are very robust in their use.Normally you just have a little code snippet (e.g. ip-blocking snippets). Through this type of programming you have whole functions.
26-May-2004 08:29

Very clever unless you need to specify at least two parameters of the same type - which is which? Obviously, you may decide on some defaults, but then the whole thing gets ugly. What if you need a string ONLY if a boolean was also supplied? The type-checking becomes the main focus of your function, shit. For the sake of clean code you should specify a clean interface to your functions, and decide on what and where is passed as an argument. Yes, you can always code a do_absolutely_everything() function, but is there any sense?
anders at ingemann dot fakestuff dot de
30-Apr-2004 03:18

A pretty cool thing for user defined functions is only to submit the needed parameters. If you call a function that has three optional parameters you have to define the two first ones (even if they should stay like the defined standard in the function) before your are able to tell the function what the third important parameter is. Instead you might as well just find out by the pattern or the type of the submitted parameter which variable it should be assigned to.
like this:


Now you can call the function with any parameter you want.
e.g.:

in that case $limit would be defined with 3600.

It doesn"t matter if you do this:


or this:

or this:

You may also use ereg (). Through that you"re able to use more than one parameter as a string.
hmm probably ereg () is the best solution...
never mind.
just check it out ;-)
mightye (at) mightye (dot) org
12-Mar-2004 08:45

func_get_arg () returns a * copy * of the argument, to my knowledge there is no way to retrieve references to a variable number of arguments.

I have a module system in my game at where I"d like to be able to pass a variable number of arguments to functions in a module, and pass them by reference if the module asks for it by reference, but you can"t accept optional parameters as references, nor can you retrieve the reference on a variable number of arguments. Looks like my modules will have to do with out the ability to accept parameters to their functions by reference.
martin at classaxe dot com
07-Jun-2002 09:55

This function whilst elegant doesn"t in itself avoid the problem of generating warning messages where variables are not set, unless of course you switched warnings off:
error_reporting (E_ERROR);

The answer for those of who like to see necessary warnings?
Call it like this:
@allSet($w , $x , $y , $z )

Когда планируется внести изменения на веб сайт, всегда полезно услышать, что думают посетители о новых функциях и особенностях. Очень долго разработчики были ограничены только использованием контактной формы, в надежде на то, что обратная связь с пользователем сработает, что, к сожалению, не всегда приносило результат.

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

XHTML

Используем новый тип документа HTML5, определяем секцию head, вставляем тег title , основную таблицу стилей - styles.css .

demo.php Рекомендации на будущее (используем PHP, jQuery и MySQL) | сайт have_voted ? "inactive" : "active").""> ".$this->suggestion." ".(int)$this->rating." "; } }

Метод __toString() используется для создания представления объекта в виде строки. Таким образом мы можем построить разметку HTML, включая заголовок предложения и количество голосов.

Метод __get() используется для предоставления доступа к неопределённым свойствам класса для массива $data . Это означает, что если мы хотим получить доступ к $obj->suggestion , а данное свойство не определено, то оно будет получено из массива $data и возвращено так, как будто оно существует. Таким образом мы можем передать массив конструктору, вместо того, чтобы устанавливать все свойства. Мы используем такой подход, когда создаем объект в ajax.php .

Теперь перейдем к генерированию неупорядоченного списка для страницы.

demo.php require "connect.php"; require "suggestion.class.php"; // Конвертируем IP в число. Это более эффективный способ хранения IP // в базе данных: $ip = sprintf("%u",ip2long($_SERVER["REMOTE_ADDR"])); // Следующий запрос использует left join для выбора // всех предложений и одновременно определяет, // голосовал ли пользователь за них. $result = $mysqli->query(" SELECT s.*, if (v.ip IS NULL,0,1) AS have_voted FROM suggestions AS s LEFT JOIN suggestions_votes AS v ON(s.id = v.suggestion_id AND v.day = CURRENT_DATE AND v.ip = $ip) ORDER BY s.rating DESC, s.id DESC "); $str = ""; if(!$mysqli->error) { // Генерируем UL $str = "
    "; // Используем метод MySQL fetch_object для создания нового объекта // и наполнения его столбцами результата запроса: while($suggestion = $result->fetch_object("Suggestion")){ $str.= $suggestion; // Используем метод __toString(). } $str .="
"; }

После выполнения запроса мы используем метод fetch_object() объекта $result . Данный метод создает объект заданного класса для каждой строки результата запроса, и назначает столбцы каждой строчки как публичные свойства объекта.

PHP также управляет запросами AJAX, отправляемыми jQuery. Это реализовано в ajax.php . Для разделения действий AJAX, скрипт использует параметр $_GET["action"] , который может иметь одно из двух значений - ‘vote ‘ или ‘submit ‘.

ajax.php require "connect.php"; require "suggestion.class.php"; // если запрос пришел не от AJAX, то выходим: if($_SERVER["HTTP_X_REQUESTED_WITH"] !="XMLHttpRequest"){ exit; } // Конвертируем IP в число. Это более эффективный способ хранения IP в базе данных: $ip = sprintf("%u",ip2long($_SERVER["REMOTE_ADDR"])); if($_GET["action"] == "vote"){ $v = (int)$_GET["vote"]; $id = (int)$_GET["id"]; if($v != -1 && $v != 1){ exit; } // Проверяем, существует ли такой id предложения: if(!$mysqli->query("SELECT 1 FROM suggestions WHERE id = $id")->num_rows){ exit; } // Поля id, ip и day является основным ключем. // Запрос потерпит неудачу, если мы будем пытаться вставить дупликат ключа, // что означает возможность для пользователя голосовать только один раз в день. $mysqli->query(" INSERT INTO suggestions_votes (suggestion_id,ip,day,vote) VALUES ($id, $ip, CURRENT_DATE, $v) "); if($mysqli->affected_rows == 1) { $mysqli->query(" UPDATE suggestions SET ".($v == 1 ? "votes_up = votes_up + 1" : "votes_down = votes_down + 1").", rating = rating + $v WHERE id = $id "); } } else if($_GET["action"] == "submit"){ if(get_magic_quotes_gpc()){ array_walk_recursive($_GET,create_function("&$v,$k","$v = stripslashes($v);")); } // Зачищаем контент $_GET["content"] = htmlspecialchars(strip_tags($_GET["content"])); if(mb_strlen($_GET["content"],"utf-8")query("INSERT INTO suggestions SET suggestion = "".$mysqli->real_escape_string($_GET["content"])."""); // Вывод HTML кода нового созданного предложения в формате JSON. // Мы используем (string) для вызова магического метода __toString(). echo json_encode(array("html" => (string)(new Suggestion(array("id" => $mysqli->insert_id, "suggestion" => $_GET["content"]))))); }

Когда jQuery отправляет запрос ‘vote ‘, не предполагается никакого возвращаемого значения, таким образом скрипт ничего не выводит. При запросе ‘submit ‘, jQuery ожидает возвращения объекта JSON, который содержит разметку HTML для предложения, которое только-что было вставлено. Именно здесь создается новый объект Suggestion с использованием магического метода __toString() и конвертированием с помощью функции json_encode() .

jQuery

Весь код jQuery располагается в файле script.js . Он отслеживает события нажатия кнопки мыши для красной и зеленой стрелочек. Но так как предложение может быть вставлено в любой момент, то используется метод jQuery live() .

script.js $(document).ready(function(){ var ul = $("ul.suggestions"); // Отслеживаем нажатие на стрелочках ВВЕРХ или ВНИЗ: $("div.vote span").live("click",function(){ var elem = $(this), parent = elem.parent(), li = elem.closest("li"), ratingDiv = li.find(".rating"), id = li.attr("id").replace("s",""), v = 1; // Если пользователь уже голосовал: if(parent.hasClass("inactive")){ return false; } parent.removeClass("active").addClass("inactive"); if(elem.hasClass("down")){ v = -1; } // Увеличиваем счетчик справа: ratingDiv.text(v + +ratingDiv.text()); // Помещаем все элементы LI в массив // и сортируем его по количеству голосов: var arr = $.makeArray(ul.find("li")).sort(function(l,r){ return +$(".rating",r).text() - +$(".rating",l).text(); }); // Добавляем отсортированные элементы LI в UL ul.html(arr); // Отправляем запрос AJAX $.get("ajax.php",{action:"vote",vote:v,"id":id}); }); $("#suggest").submit(function(){ var form = $(this), textField = $("#suggestionText"); // Предотвращение дублирования запросов: if(form.hasClass("working") || textField.val().length