- Не работает switch case php
- Почему switch/case выводит не заданное выражение?
- 1 ответ 1
- Всё ещё ищете ответ? Посмотрите другие вопросы с метками php или задайте свой вопрос.
- Похожие
- Подписаться на ленту
- Switch case final в PHP или почему goto это плохо
- Проблема
- Полная задача
- Вопрос
- 5 ответов 5
- Вывод
- Не работает switch case php
- Something for all three
- no match
Не работает switch case php
Здесь могла бы быть ваша реклама
Покинул форум
Сообщений всего: 4574
Дата рег-ции: Июль 2006
Откуда: Israel
Секрет
Теперь, когда вы уже наверняка второпях отправили свой запрос,
я расскажу вам простой секрет, который сэкономит вам уйму ожиданий,
даже если первый ответ по теме последуем сразу же.
Само собой я знаю что ответят мне тут же, и если я посмотрю
на сообщения на форуме, то пойму что в общем то я и не ошибаюсь.
Но еще я точно замечу, что очень мало тем, в которых всего два ответа :
вопрос автора и еще два сообщение вида Ответ + Спасибо
После этого приходится начинать уточнять этим неграмотным что мне надо.
Они что, сами читать не умеют? А уточнять приходится.
И иногда пока они переварят то что я им скажу проходит и не одна ночь..
Уверен что если бы я им сказал что у меня есть
фиолетовый квадрат, и нужно превратить его в синий треугольник
и я пытался взять кисточку, макнуть в банку и поводить ей по квадрату
но почему то кисточка не принимала цвет краски в банке,
то на мой вопрос — где взять правильные банки мне бы ответили гораздо быстрее
предложив её открыть, а не тратить еще стольник на жестянку.
Поэтому с тех пор я строю свои вопросы по проверенной давным давно схеме:
Что есть
Что нужно получить
Как я пытался
Почему или что у меня не получилось.
На последок как оно происходит на форумах
Новичок: Подскажите пожалуста самый крепкий сорт дерева! Весь инет перерыл, поиском пользовался!
Старожил: Объясни, зачем тебе понадобилось дерево? Сейчас оно в строительстве практически не используется.
Новичок: Я небоскрёб собираюсь строить. Хочу узнать, из какого дерева делать перекрытия между этажами!
Старожил: Какое дерево? Ты вообще соображаешь, что говоришь?
Новичок: Чем мне нравиться этот форум — из двух ответов ниодного конкретного. Одни вопросы неподелу!
Старожил: Не нравится — тебя здесь никто не держит. Но если ты не соображаешь, что из дерева небоскрёбы не строят, то лучше бы тебе сначала школу закончить.
Новичок: Не знаите — лучше молчите! У меня дедушка в деревянном доме живёт! У НЕГО НИЧЕГО НЕ ЛОМАЕТСЯ.
Но у него дом из сосны, а я понимаю, что для небоскрёба нужно дерево прочнее! Поэтому и спрашиваю. А от вас нормального ответа недождёшся.
Прохожий: Самое крепкое дерево — дуб. Вот тебе технология вымачивания дуба в солёной воде, она придаёт дубу особую прочность:
Новичок: Спасибо, братан! То что нужно.
Отредактировано модератором: Uchkuma, 26 Апреля, 2011 — 10:21:12
Источник
Почему switch/case выводит не заданное выражение?
Надо вывести значение post_max_size , которое указано в настройках PHP
Зачем умножать мегабайты, если потом выведет, совсем не то число?
Это по урокам специалиста, но как работает этот код, он не показал и перешёл к другой теме. Может просто, быстро показал для примера?
1 ответ 1
Вообще тут показывается работа оператора switch и, в частности, что будет, если не писать break в конце каждого case . Ибо по дефолтку, попадая в одну из веток case , если не писать break , то код будет «проваливаться» вниз и выполнять остальные ветки, игнорируя нижележащие инструкции. В этом суть данного примера (и, кстати, на сколько я помню, я видел урок и там как раз вполне всё объясняется от начала работы оператора и до задачи с информацией из файла. UPD: я даже нашел Видео — начиная с 3 минуты и до 30. разжёвано подробнейше).
Поэтому если, например, $letter == ‘G’ , то значение size умножится на 1024, потом провалится вниз к M (но буква уже не будет с ним сравниваться, а сразу исполнится инструкция), еще раз умножится, провалится к K (тоже сравниваться буква уже не будет) и умножится еще раз. В общем, итог показа будет отображение данных в байтах. Если такое поведение не нужно — ставятся «бряки».
Всё ещё ищете ответ? Посмотрите другие вопросы с метками php или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.10.15.40479
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Источник
Switch case final в PHP или почему goto это плохо
Проблема
Есть задача при использовании switch у разных case выполнять еще и код из default (или например final реализовать), что бы не дублировать одинаковый код в разных кейсах.
Если убрать break у варианта b , то будет выполнен лишний код
Есть решение через goto , что является плохим стилем кодирования:
Полная задача
Есть массив полей разных сущностей и нужно разные действия у разных полей сделать.
Вопрос
Как это сделать без использования goto ? Может есть вариант с другим подходом в архитектуре.
P.S. Если goto здесь уместен (лично я не боюсь динозавров), то почему это плохой стиль кодирования?
5 ответов 5
Зачем усложнять? Можно вынести повторяющийся код в функцию/метод класса и вызывать их из каждого кейса. Кода получится ровно столько же, зато goto мы не используем и код остаётся читаемый и легко поддерживаемый:
Если только одно действие не должно быть продолжено default , почему бы не попробовать вынести default действие за switch и огородить if ($fieldName != ‘id’)
Можно оформить условия как отдельные функции (методы).
Ключевая функция. Получает действие на входе и выполняет соответствующую функцию:
Собственно действия. Возвращают true или false как маркеры необходимости выполнять действие по умолчанию.
Функция (метод) для действия по умолчанию:
После изучения ответов, статей и умозрительных эксперементов, пришел к выводу.
Вывод
В данном случае использование goto допустимо, пока не будет добавлена подобная конструкция в синтаксис switch и если соблюдаются условия:
- Ты уже не Junior
- Переходить можно только вперёд
- Заходить в блоки и выходить категорически нельзя
Любой while и вложенные if так же опасны как goto . Для выхода из множественных циклов есть break N .
Плюсы которые я вижу
- Краткость и простота кода при соблюдении вышеописанных условиях
- Меньше занимаемой памяти и скорее всего быстрота выполнения
- Лучше «плохой тон», чем много избыточного кода, который сложнее поддерживать
Для себя я решил использовать только в группах исключающих условий:
Конечно при усложнении логики и увеличении строк кода, лучше всего воспользоваться ответом n4nn31355 и выносить в классы и отдельные методы, но внутри у них все равно наверно будет что-то похожее 😉
Источник
Не работает switch case php
switch (‘aaaaa’) <
default : echo «DEFAULT TOP 1»; break;
default : echo «DEFAULT TOP 2»; break;
case ‘aaaaa’: echo «CASE TOP 1»; break;
case ‘aaaaa’: echo «CASE TOP 2»; break;
default : echo «DEFAULT BOTTOM 1»; break;
default : echo «DEFAULT BOTTOM 2»; break;
case ‘aaaaa’: echo «CASE BOTTOM 1»; break;
case ‘aaaaa’: echo «CASE BOTTOM 2»; break;
>
//return ——> CASE TOP 1
switch (‘SOMETHING_THAT_DOESN_T_EXIST’) <
default : echo «DEFAULT TOP 1»; break;
default : echo «DEFAULT TOP 2»; break;
case ‘aaaaa’: echo «CASE TOP 1»; break;
case ‘aaaaa’: echo «CASE TOP 2»; break;
default : echo «DEFAULT BOTTOM 1»; break;
default : echo «DEFAULT BOTTOM 2»; break;
case ‘aaaaa’: echo «CASE BOTTOM 1»; break;
case ‘aaaaa’: echo «CASE BOTTOM 2»; break;
>
//return ——> DEFAULT BOTTOM 2
Some observations:
— no errors if several identical boxes or defaultes
— the last defect takes over
— the first of the boxes takes the hand
— we can put the default at the top (indeed sometimes it’s more intuitive)
Rewriting the function (to be three times faster) provided by [stever at ashomecare dot com 07-Sep-2007 09:11] and demonstrating points that others have made:
function getChineseZodiac ( $year )<
switch ( $year % 12 ) :
case 0 : return ‘Monkey’ ; // Years 0, 12, 1200, 2004.
case 1 : return ‘Rooster’ ;
case 2 : return ‘Dog’ ;
case 3 : return ‘Boar’ ;
case 4 : return ‘Rat’ ;
case 5 : return ‘Ox’ ;
case 6 : return ‘Tiger’ ;
case 7 : return ‘Rabit’ ;
case 8 : return ‘Dragon’ ;
case 9 : return ‘Snake’ ;
case 10 : return ‘Horse’ ;
case 11 : return ‘Lamb’ ;
endswitch;
>
echo getChineseZodiac ( 2016 );
?>
Be very careful when you’re using text strings as cases. If the variable supplied to switch() is an integer, the cases would be converted to integer before the comparison is made (usually to zero). The following snippet prints «hello».
= 0 ;
switch( $a ) <
case ‘Hello’ : echo «Hello» ;
break;
>
?>
Be careful if you have mixed types of values in the switch statement. Explicitly cast your variables where possible to avoid mismatch:
// This match case #1
// switch ( $var )
// This works as expected
switch ( (string) $var )
<
case «0string» :
echo «0string match» ;
break;
>
?>
It’s easy to abuse the switch syntax to do some very useful things. As this example will show, the possibilities can go beyond even Duff’s Device-style craziness (not that this example is nearly as clever as Duff’s Device, but it demonstrates how you can do certain things other than simply the increment/decrement/assignment that’s possible in C).
Fundamentally, this works mostly due to the fact that, from the point of view of the assembler/interpreter, a switch block is hardly any different from a bunch of GOTO labels and if() evaluations. But, like an if() evaluation, the line of a case: statement is evaluated as an expression. So, in this case, we can perform an assignment and match the result of that assignment, because the return value of an assignment is the data that was assigned (and not the value of the variable it was assigned to, as you might expect).
So far, this is not actually amazing, even if it is a bit unintuitive. From a language point-of-view, it would be the same as an if($var = «string») statement which is using an assignment (=) rather than a comparison (==) operator. When you look at the pre-processing optimization, because a normal assignment of $var = «string» will always equal «string», it makes sense to have the result of that expression simply be equal to the right side of the expression (the right side is used rather than the left to let the assembler/interpreter work faster, on account of how they traditionally simply change the memory location for the assigned variable rather than copy the memory around unnecessarily).
Where this becomes more interesting is where, in PHP, you have language constructs that behave like functions but are used like statements. An $array[] = «string» expression is actually a language construct that just happens to behave a lot like a function, but you use it in the same way that you use an assignment expression, and like an expression, it always evaluates to the right side of the expression; in this case, «string» and not array() .
The assembler/interpreter can’t use the right side of the expression as a shortcut for the result of a function, so you can’t use functions in this way in a case statement. You also can’t get around this limit on calling functions from the case line by using variable functions, because they are used in the same way as functions.
But imagine what you could do with other language constructs, like eval() or include() !
Consider the following:
function flavor ( $type = null )
<
switch ( $type ) <
/* Note the isolation of break; statements and the fact that default: is at the top */
default:
$type = null ;
case $array [] = «chocolate» :
if ( $type != null ) <
$array = array( $type );
break;
>
case $array [] = «strawberry» :
if ( $type != null ) <
$array = array( $type );
break;
>
case $array [] = «vanilla» :
if ( $type != null ) <
$array = array( $type );
break;
>
>
if ( ( count ( $array ) != 1 ) ) <
return «Flavors available: » . implode ( «, » , $array );
> else <
return «Flavor selected: » . implode ( «, » , $array );
>
>
echo flavor () . «
» ;
/* Flavors available: chocolate, strawberry, vanilla */
echo flavor ( «banana» ) . «
» ;
/* Flavors available: chocolate, strawberry, vanilla */
echo flavor ( «chocolate» ) . «
» ;
/* Flavor selected: chocolate */
?>
What makes this example useful is that you don’t need a variable somewhere that contains the available options (even within the function itself), so to support new options, you only ever have to change the code to add the new option — you don’t need to update some variable somewhere that controls whether or not it works or whether or not people can tell that there’s a new option.
You can also nest switch statements inside case statements:
// Set argument handlers
$argv = explode ( «,» , urldecode ( getenv ( ‘QUERY_STRING’ )));
$argc = array_shift ( $argv );
$argd = array_shift ( $argv );
$arge = array_shift ( $argv );
?>
// Begin switching
switch ( $argc ) <
case ‘home’ : <
print( ‘This is $argc, home case.’ );
break;
>
case ‘subsection’ : <
switch ( $argd ) <
case ‘links’ : <
switch( $arge ) <
case ‘display’ : <
print( ‘This is $arge, subsection,links,display case.’ );
break;
>
>
>
>
>
>
?>
As follow-up to ben dot lancaster at holler dot co dot uk’s post:
‘continue’ ends the switch, not the case, just as it would with any other flow control. Think of it as putting the execution pointer right before the ending accolade (that is, the >) because that is essentially what happens. In the case of a for loop, this would cause the iteration clause to execute, and if applicable, the loop to begin again. However, switches do not loop, which is why (as noted above, in the manual!) a continue statement essentially acts as a break when within a switch.
Not sure if this has been posted or not, but I found the switch statement useful for finding ranges of data.
This script creates web 2.0 style links in different font sizes (popular on blogs) using a randomizer and switch statement. I used links from within a database for a mod I made for a Simple Machines forums, but this example uses arrays for links if you wanted to add your own custom links:
// Create set of links
$link = array();
$link [] = ‘page 1’ ;
$link [] = ‘page 2’ ;
$link [] = ‘page 3’ ;
$link [] = ‘page 4’ ;
$link [] = ‘page 5’ ;
$link [] = ‘page 6’ ;
$link [] = ‘page 7’ ;
$link [] = ‘page 8’ ;
// Create loop to display links
for( $i = 0 ; $i count ( $link ); ++ $i )
<
// Create randomizer
// Use switch statement to find font size
$randomizer = rand ( 1 , 50 );
switch( $randomizer )
<
case ( $randomizer 20 ):
$font_size = «11» ;
break;
case ( $randomizer 30 ):
$font_size = «16» ;
break;
case ( $randomizer 40 ):
$font_size = «18» ;
break;
case ( $randomizer 50 ):
$font_size = «20» ;
break;
>
// Display the link
echo ‘ . $font_size . ‘;»>’ . $link [ $i ]. ‘ ‘ ;
// Loop the next link
>
?>
Using this type of range randomizer is useful for game development and it can be useful on the web too, for things where you don’t want to use a randomizer just for things like (1-5) where you wanted a more then likely result for one thing over another. The switch statement saves from writing spaghetti code if statements.
In case : ) it helps someone, I was able to clean up some hairball code by using nested switches (didn’t see it mentioned here). Thanks to all those who are writing examples — I love this site!
= «second» ;
switch ( $string_match ) <
case «first» :
case «second» :
case «third» :
print «
Something for all three
no match
echo $foo ; // will produce «not a number»
/* script 2 */
$foo = «not a number» ;
$arr = array( «not a number» ); // 1 element only !
switch( $arr [ 1 ]) // element $foo[1] doesn’t defined
<
case «1» : < $foo = "1" ; break; >
case «2» : < $foo = "2" ; break; >
default: < $foo = "0" ; >
>
echo $foo ; // will produce «not a number» ( not 0 ! )
/* script 3 */
$foo = «not a number» ;
$arr = array( «not a number» ); // 1 element only !
switch( $arr [ 1 ]? $arr [ 1 ]: «1» ) // element $foo[1] doesn’t defined
<
case «1» : < $foo = "1" ; break; >
case «2» : < $foo = "2" ; break; >
default: < $foo = "0" ; >
>
echo $foo ;
// will produce :
// 1 if $arr[1] isn’t set
// 1 if $arr[1]=1
// 2 if $arr[1]=2
// 0 if none of above
?>
If you want to avoid numeric compare for numeric strings in switch statement, try prepending something non-numeric.
e.g.
= ‘2’ ;
switch( $val )<
case ‘2.0’ : echo ‘2.0. ‘ ; break;
case ‘2’ : echo ‘2.’ ; break;
>
?>
echoes ‘2.0. ‘ ; while prepended version
= ‘2’ ;
switch( ‘#’ . $val )<
case ‘#2.0’ : echo ‘2.0. ‘ ; break;
case ‘#2’ : echo ‘2.’ ; break;
>
?>
echoes ‘2.’.
Example of default NOT included as the last item
switch( 5 ) <
case 1 :
echo «1» ;
break;
case 2 :
default:
echo «2, default» ;
break;
case 3 ;
echo «3» ;
break;
>
?>
Outputs ‘2,default’
very useful if you want your cases to be presented in a logical order in the code (as in, not saying case 1, case 3, case 2/default) and your cases are very long so you do not want to repeat the entire case code at the bottom for the default
Regarding [php_net at mcdragonsoftware dot com 17-Jun-2011 09:53]; the elegant function and syntax provided for an «inline switch» statement is more readable and about 25% faster than this alternative (that uses existing builtin functions), which produces the same result:
echo array_pop ( array_slice (array( ‘rock’ , ‘paper’ , ‘scissors’ ), — $roll , 1 )); ?>
Haven’t seen it mentioned here, but at least in my version (PHP 5.2.5) and I’m sure all of PHP 5, the switch statement is a great way to check type safe enumerates that are otherwise missing in the PHP language. Example:
class WannabeEnum <
/**
* @var WannabeEnum
*/
public static $FOO ;
/**
* @var WannabeEnum
*/
public static $BAR ;
/**
* @var WannabeEnum
*/
public static $FOOBAR ;
private $_ordinal ;
public function __construct ( $ordinal ) <
$this -> _ordinal = $ordinal ;
>
>
WannabeEnum :: $FOO = new WannabeEnum ( 1 );
WannabeEnum :: $BAR = new WannabeEnum ( 2 );
WannabeEnum :: $FOOBAR = new WannabeEnum ( 3 );
function testSwitch ( WannabeEnum $wannabeEnum ) <
switch( $wannabeEnum ) <
case WannabeEnum :: $FOO :
echo( ‘Foo!’ . PHP_EOL );
break;
case WannabeEnum :: $BAR :
echo( ‘Bar!’ . PHP_EOL );
break;
default:
echo( ‘Default!’ . PHP_EOL );
>
>
testSwitch ( WannabeEnum :: $FOO );
testSwitch ( WannabeEnum :: $FOOBAR );
?>
Outputs:
Don’t forget it uses loose comparisons!
working a bit around with it I found out that it is not possible to
compare the variable with two different values in one step like this
(system running a w2k server, apache2.0.43 & php430):
switch ( $myvar ) <
case ( «foo» || «bar» ): //do something
break;
case ( «other» ): //do another thing
break;
default:
>
?>
rather use:
switch ( $myvar ) <
case ( «foo» ):
case ( «bar» ): //do something
break;
case ( «other» ): //do another thing
break;
default:
>
?>
often you will have to perform multiple actions in sequence, but this sequence must be broken once one of them detects a stop condition (such as an error, when validating form request variables).
One way is to use:
But when the sequence is long and must reordered, this can be errorprone because not all line of check have the same syntax (imagine that you want to comment one of them).
Another way is to rewrite it as:
check1() and
check2() and
check3() and
.
valid() or
error();
The above syntax does not fit well when the valid() code must be several statements.
An alternative syntax can be:
switch (false) <
case check1():
case check2():
case check3():
error();
break;
default:
valid();
>
This last equivalent sample show you that each case expressions is evaluated, until one of them evaluates to a value equal (==) to the switch expression. Above, the error() code will only be called if one of the check evaluates to false. And the valid() code will only be evaluated only if the switch reach the default, which means that none of the above check returned false.
In response to the entry by «kriek at jonkriek dot com», I think you would probably be better of doing this:
// ensure $_GET[‘go’] is set, an integer, and not 0
// then, set nav number; default to 1
$nav = ( isset( $_GET [ ‘go’ ]) && ( intval ( $_GET [ ‘go’ ]) == $_GET [ ‘go’ ]) && $_GET [ ‘go’ ] ) ?
intval ( $_GET [ ‘go’ ]) : 1 ;
// format navigation string and include
include( sprintf ( «Page%02d.php» , $nav ));
?>
. as oppposed to the switch setup you recommended, which is limited to the number of cases you specify.
In answer to njones at fredesign dot com, what you’re seeing is the way the switch statement is supposed to work. The switch statement evaluates the cases, top to bottom, until it finds the first one that matches the value being switch()ed on. So, for example, if you had:
switch( 2 ) <
case 1 : echo «One\n» ; break;
case 2 : echo «Two\n» ; break;
case 3 : echo «Three\n» ; break;
case 2 : echo «Two again\n» ; break;
>
?>
Only «Two» would get echoed. «Two again» would NOT get echoed, because once the first case matches, the rest of them do NOT get evaluated. As soon as a matching case is found, the statements starting at that case get executed until the first break, then control flows out the bottom of the switch block.
Switch usage for make some actions with all of cases
= ‘ ‘ ;
for ( $i = 1 ; $i 10 : $i ++) <
switch ( $i ) <
case true : $out .= ‘test_’ ;
case 1 :
case 2 :
case 3 : $out .= $i ;
default: $out .= ‘ ‘ ;
>
>
echo $out ;
?>
That sample out:
» test_1 test_2 test_3 «
«loose comparison» means that switch won’t check the type.
switch will only compare values:
if( ‘a string’ == 0 ) echo ‘a string is 0’ . PHP_EOL ;
if( ‘a string’ === 0 ) echo ‘but you will never see this’ . PHP_EOL ;
switch( 0 ) <
case ‘a string’ : echo ‘a string’ . PHP_EOL ;
case ‘another string’ : echo ‘another string’ . PHP_EOL ;
>
if( ‘a string’ == true ) echo ‘a string is TRUE’ . PHP_EOL ;
if( ‘a string’ === true ) echo ‘but you will never see this’ . PHP_EOL ;
switch( true ) <
case ‘a string’ : echo ‘a string’ . PHP_EOL ;
case ‘another string’ : echo ‘another string’ . PHP_EOL ;
>
?>
will output:
a string is 0
a string
another string
a string is TRUE
a string
another string
Did you know that switch() and case() can also accomodate things like basic math calculations and counter incrementing? They do. In this example, I use a switch statement (which is inside of a while loop) to alternate the background color of a table row. It gives me a cool spool-printer-paper effect.
= 5 ; // change bgcolor every 5 rows
switch( $ctr ++) <
case 0 :
$bgcolor = «#ffffff» ;
break;
case ( $rows_per_color ):
$bgcolor = «#ff0000» ;
break;
case ( $rows_per_color * 2 ):
$bgcolor = «#ffffff» ;
$ctr = 1 ;
break;
>
?>
As you can see, I increment $ctr by 1 in the switch() itself, and the final case() does a simple calculation. Simple, but powerful. [Remember, the above example is inside of a while() loop. each time it iterates, switch increments $ctr.]
In reply to earlier comment, «switch»- I found this to be one of the best ways to interpret ‘actions’. Simply create a new instance of Handler_action before including any content source files. This is a highly stripped version of the class.
The real one I created handles (and secures) input for $_GET and $_POST, creates a ‘permission’ array that only allows certain actions to be called by non-admins, and creates handy little diagnostic messages that can be displayed upon redirecting.
On that note, the beauty in this class really shines in the simple redirect. You wont be left with ugly URLs like, «http://www.domain.com/path/to/script.php?action=blah&var1=123». Rather, you will be left with something like «http://www.domain.com/path/to/script.php»- helps protect some of the site by not showing any vulnerabilities in URLs.
Also, this class keeps all actions organized neatly by directly passing $_GET vars to the actions through function parameters.
class Handler_action <
function __construct ( ) <
//Add code here to secure attacks through $_GET or use $_POST
$action = $_GET [ «action» ];
//$actions_index conventions:
//’action_name’ => array( ‘arg1’, ‘arg2’, ‘etc’, [‘/redirect/to/path’ | NULL ] )
$actions_index = array(
‘create’ => array( $_GET [ ‘newVar1’ ], $_GET [ ‘newVar2’ ], ‘/home.php’ ),
‘edit’ => array( $_GET [ ‘id’ ], $_GET [ ‘otherVar’ ], ‘/home.php’ ),
‘delete’ => array( $_GET [ ‘id’ ], ‘/other_script.php’ )
);
//being defining actions now
function create ( $new_var1 , $new_var2 )<
>
function edit ( $id , $other_var )<
Источник