![](/img/trans.png)
[英]storing value return by function in variable of if statement and use in other condition -php
[英]php function return a Boolean and use it on condition
我不確定我將如何正確解釋這一點。
我想要一個函數來驗證我認為正確的字符串。
但我希望函數返回一個布爾值。
在函數外部我需要創建一個條件,如果函數返回false,或者true,那將會執行某些操作。 這是我的代碼。
我不確定這是否正確。
<?php
$string1 = 'hi';
function validatestring($myString, $str2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
}
}
else {
return false;
}
}
if(validatestring == FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
編輯:現在如果函數內有多個條件怎么辦?
<?php
$string1 = 'hi';
function validatestring($myString, $myString2) {
if(!empty($myString)) {
if(preg_match('/^[a-zA-Z0-9]+$/', $str2)) {
return true;
}
else {
retun false;
}
}
else {
return false;
}
}
if(validatestring($myString, $myString2) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
<?php
$string1 = 'hi';
function validatestring($myString) {
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring($string1) === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
功能需要括號和參數。 你沒有任何一個。
這是正確的:
if(validatestring($myString) === false) {
//put some codes here
}
一種更簡單,更優雅的方法是:
if(!validatestring($myString)) {
//put some codes here
}
旁注,因為empty()
已經返回false
,你可以通過這樣做來簡化:
function validateString($string){
return !empty($string);
}
if(validateString($myString){
// ok
}
else {
// not ok
}
要稍后進行檢查和測試:
$check = validateString($myString);
if($check){ }
沒有必要檢查== false
或=== false
,該函數已經返回一個布爾值,它將是多余的。
在函數myString = string1中將$ string1存儲到$ myString
<?php
$string1 = 'hi';
function validatestring($myString) {
myString=string1;
if(!empty($myString)) {
return true;
}
else {
return false;
}
}
if(validatestring() === FALSE) {
//put some codes here
}
else {
//put some codes here
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.