Значение переменной по умолчанию, если она не установлена

Статус
В этой теме нельзя размещать новые ответы.

mike345

Полезный
Регистрация
9 Авг 2009
Сообщения
175
Реакции
18
Hi, All!

В sh есть возможность назначить значение переменной если она не установлена с помощью:
${var:=value}
Есть ли похожая конструкция в PHP (кроме isset и других более громоздких вариантов)?
 
PHP:
function myFunction( $var = 55 )  // $var по умолчанию равно 55
{
   return  $var;
}
ну и если вызывать то
echo myFunction() соответственно выведет 55
а
echo myFunction(22) соответственно выведет 22
если в ф-ции есть несколько входных значений среди которых есть те которые имеют значения по-умолчанию то их нужно писать последними ( это не требования пхп-интерпретатора, а просто негласное правило )
т.е.
PHP:
function myFunction( $var = 55,  $var1, $var2 ) // верно 
function myFunction( $var1, $var2,  $var = 55 ) // не верно
 
Не совсем про то я...
В SH:
echo "${var:=55}";
выведет 55, если до этого переменная $var была не определена или имеет значение null.
Если же до этого где либо было указано $var=66;
то echo "${var:=55}"; выведет 66...
==============
Расширим вопрос, есть подобное следующему?

${ parameter :- word }
Use Default Values. If parameter is unset or null, the expansion of word is substituted; otherwise, the value of parameter is substituted.
${ parameter := word }
Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter In all cases, the final value of parameter is substituted. Only variables, not positional parameters or special parameters, can be assigned in this way.
${ parameter :? [word } ]
Indicate Error if Null or Unset. If parameter is unset or null, the expansion of word (or a message indicating it is unset if word is omitted) is written to standard error and the shell exits with a nonzero exit status. Otherwise, the value of parameter is substituted. An interactive shell need not exit.
${ parameter :+ word }
Use Alternate Value. If parameter is unset or null, null is substituted; otherwise, the expansion of word is substituted.
In the parameter expansions shown previously, use of the colon in the format results in a test for a parameter that is unset or null; omission of the colon results in a test for a parameter that is only unset.
${# parameter }
String Length. The length in characters of the value of parameter
The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Sx Shell Patterns ) , rather than regular expression notation, is used to evaluate the patterns. If parameter is one of the special parameters * or @ the result of the expansion is unspecified. Enclosing the full parameter expansion string in double-quotes does not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces has this effect.
${ parameter % word }
Remove Smallest Suffix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter with the smallest portion of the suffix matched by the pattern deleted.
${ parameter %% word }
Remove Largest Suffix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter with the largest portion of the suffix matched by the pattern deleted.
${ parameter # word }
Remove Smallest Prefix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter with the smallest portion of the prefix matched by the pattern deleted.
${ parameter ## word }
Remove Largest Prefix Pattern. The word is expanded to produce a pattern. The parameter expansion then results in parameter with the largest portion of the prefix matched by the pattern deleted.
 
echo ($var!=null)? $val:55;
 
В sh есть возможность назначить значение переменной если она не установлена с помощью:
${var:=value}
Есть ли похожая конструкция в PHP (кроме isset и других более громоздких вариантов)?

Если переменная не обьявленна то она имеет какое-то значение... В пхп такого еще не встерчал. Если переменная не установленна, то соответсвено ее нету и не может что либо содержать.
 
Если переменная не обьявленна то она имеет какое-то значение... В пхп такого еще не встерчал. Если переменная не установленна, то соответсвено ее нету и не может что либо содержать.
Как это не встречали?
Если переменная не объявлена, то она имеет значение NULL ;)
 
Вопрос был про то, что в shell переменная вида: ${var:=value}
имеет значение "value", если ей не присвоено значение ранее или она не объявлена.
 
Статус
В этой теме нельзя размещать новые ответы.
Назад
Сверху