Рекомендации на будущее с системой голосования. Php ошибка - Недопустимый аргумент для foreach()

Is it possible in PHP 4/5 to specify a named optional parameter when calling, skipping the ones you don’t want to specify (like in python) ?

Function foo($a,$b="", $c="") { // whatever } foo("hello", $c="bar"); // we want $b as the default, but specify $c

No, it is not possible: if you want to pass the third parameter, you have to pass the second one. And named parameters are not possible either.

A “solution” would be to use only one parameter, an array, and always pass it… But don’t always define everything in it.

Function foo($params) { var_dump($params); }

And calling it this way:

Foo(array("a" => "hello",)); foo(array("a" => "hello", "c" => "glop",)); foo(array("a" => "hello", "test" => "another one",));

Will get you this output:

Array "a" => string "hello" (length=5) array "a" => string "hello" (length=5) "c" => string "glop" (length=4) array "a" => string "hello" (length=5) "test" => string "another one" (length=11)

But I don’t really like this solution:

  • You will lose the phpdoc
  • Your IDE will not be able to provide any hint anymore… Which is bad

So I’d go with this only in very specific cases — for functions with lots of optionnal parameters, for instance…

No, PHP cannot pass arguments by name.

If you have a function that takes a lot of arguments and all of them have default values you can consider making the function accept an array of arguments instead:

Function test (array $args) { $defaults = array("a" => "", "b" => "", "c" => ""); $args = array_merge($defaults, array_intersect_key($args, $defaults)); list($a, $b, $c) = array_values($args); // an alternative to list(): extract($args); // you can now use $a, $b, $c }

The only way you can somewhat do that is by using arrays with named keys and what not.

With PHP, the order of arguments is what matters. You can’t specify a particular argument out of place, but instead, you can skip arguments by passing a NULL, as long as you don’t mind the value in your function having a NULL value.

Foo("hello", NULL, "bar");

As of PHP 5.4 you have shorthand array syntax (not nessecary to specify arrays with cumbersome “array” and instead use “”).

You can mimic named parameters in many ways, one good and simple way might be:

Bar("one", ["a1" => "two", "bar" => "three", "foo" => "four"]); // output: twothreefour function bar ($a1, $kwargs = ["bar" => null, "foo" => null]) { extract($kwargs); echo $a1; echo $bar; echo $foo; }

It’s not exactly pretty, but it does the trick, some might say.

Class NamedArguments { static function init($args) { $assoc = reset($args); if (is_array($assoc)) { $diff = array_diff(array_keys($assoc), array_keys($args)); if (empty($diff)) return $assoc; trigger_error("Invalid parameters: ".join(",",$diff), E_USER_ERROR); } return array(); } } class Test { public static function foobar($required, $optional1 = "", $optional2 = "") { extract(NamedArguments::init(get_defined_vars())); printf("required: %s, optional1: %s, optional2: %s\n", $required, $optional1, $optional2); } } Test::foobar("required", "optional1", "optional2"); Test::foobar(array("required" => "required", "optional1" => "optional1", "optional2" => "optional2"));

You can keep the phpdoc and the ability to set defaults by passing an object instead of an array, e.g.

Class FooOptions { $opt1 = "x"; $opt2 = "y"; /* etc */ };

That also lets you do strict type checking in your function call, if you want to:

Function foo (FooOptions $opts) { ... }

Of course, you might pay for that with extra verbosity setting up the FooOptions object. There’s no totally-free ride, unfortunately.

Normally you can’t but I think there a lot of ways to pass named arguments to a PHP function. Personally I relay on the definition using arrays and just call what I need to pass:

Class Test{ public $a = false; private $b = false; public $c = false; public $d = false; public $e = false; public function _factory(){ $args = func_get_args(); $args = $args; $this->a = array_key_exists("a",$args) ? $args["a"] : 0; $this->b = array_key_exists("b",$args) ? $args["b"] : 0; $this->c = array_key_exists("c",$args) ? $args["c"] : 0; $this->d = array_key_exists("d",$args) ? $args["d"] : 0; $this->e = array_key_exists("e",$args) ? $args["e"] : 0; } public function show(){ var_dump($this); } } $test = new Test(); $args["c"]=999; $test->_factory($args); $test->show();

If I have to pass 10 arguments, and 3 of them are the data I really need, is NOT EVEN SMART to pass into the function something like

Return myfunction(false,false,10,false,false,"date",false,false,false,"desc");

With the approach I’m giving, you can setup any of the 10 arguments into an array:

$arr["count"]=10; $arr["type"]="date"; $arr["order"]="desc"; return myfunction($arr);

I have a post in my blog explaining this process in more details.

Here’s what I’ve been using. A function definition takes one optional array argument which specifies the optional named arguments:

Function func($arg, $options = Array()) { $defaults = Array("foo" => 1.0, "bar" => FALSE); $options = array_merge($default, $options); // Normal function body here. Use $options["foo"] and // $options["bar"] to fetch named parameter values. ... }

You can normally call without any named arguments:

Func("xyzzy")

To specify an optional named argument, pass it in the optional array:

Func("xyzzy", Array("foo" => 5.7))

No not really. There are a few alternatives to it you could use.

Test(null,null,"hello")

Or pass an array:

Test(array("c" => "hello"));

Then, the function could be:

Function test($array) { $c = isset($array[c]) ? $array[c] : ""; }

Or add a function in between, but i would not suggest this:

Function ctest($c) { test("","",$c); }

Try function test ($a="",$b="",&$c=""){}

Putting & before the $c

I dont think so…
If you need to call, for example, the substr function, that has 3 params, and want to set the $length without set the $start, you’ll be forced to do so.

Substr($str,0,10);

a nice way to override this is to always use arrays for parameters

Simple answer. No you can’t.
You could try getting around it by passing in an object/array or using some other Dependency injection patterns.

Also, try to use nulls rather than empty strings as it’s more definite to test for their existence using is_null()

Function test ($a=null,$b=null,$c=null){ if (is_null($a) { //do something about $a } if (is_null($b) { //do something about $b } if (is_null($c) { //do something about $c } }

Test(null,null,"Hello");

In very short, sometimes yes, by using reflection and typed variables. However I think this is probably not what you are after.

A better solution to your problem is probably to pass in the 3 arguments as functions handle the missing one inside your function yourself

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