Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在php中测试时在条件中定义变量_Php - Fatal编程技术网

在php中测试时在条件中定义变量

在php中测试时在条件中定义变量,php,Php,是否可以调用条件中的方法进行测试,但也可以将返回存储在同一条件中的var中,从而减少api调用? 例如: elseif( ($auth_type = \proj101\user::getUserAuthType( $user_profile['email'] ) ) && $auth_type != AUTH_TYPE_GOOGLE ){ //$auth_type now equals the function return and n

是否可以调用条件中的方法进行测试,但也可以将返回存储在同一条件中的var中,从而减少api调用? 例如:

elseif( 
        ($auth_type = \proj101\user::getUserAuthType( $user_profile['email'] ) ) 
        && $auth_type != AUTH_TYPE_GOOGLE  
){
  //$auth_type now equals the function return and not just 'true'

是的,你可以这样做,你只需要确定正确的操作顺序。由于赋值的优先级低于逻辑
&&
,因此您最终会将auth_type设置为
&&
操作的结果

考虑这个简单的例子:

<?php
const AUTH_TYPE_GOOGLE = 1;
function userAuthTypeStub( $x ){
    return 2;
}
if( 0 ){
    // who knows what to do?
}
elseif(
    $auth_type = userAuthTypeStub( 0 )
    && $auth_type != AUTH_TYPE_GOOGLE
){
    echo "$auth_type\n" . userAuthTypeStub(0) . "\n";
}
但如果你确定了操作顺序,你就会得到你所期望的:

<?php
const AUTH_TYPE_GOOGLE = 1;
function userAuthTypeStub( $x ){
    return 2;
}
if( 0 ){
    // who knows what to do?
}
elseif(
    ( $auth_type = userAuthTypeStub( 0 )  )
    && ( $auth_type != AUTH_TYPE_GOOGLE )
){
    echo "$auth_type\n" . userAuthTypeStub(0) . "\n";
}

2
2

如果我理解正确,在elseif条件下,您将$auth_type的值定义为getUserAuthType(…)函数的返回值,然后检查新返回的值是否不等于“auth_type_GOOGLE”。这在理论上可能是可行的,但以这种方式编写PHP代码是一种不好的做法,它需要花费大量的时间来查看代码,以便理解它,尝试将其划分为多个if条件。这种方法可行,但不是好的风格。一个原因是,一种常见的打字错误是在你真正想说的地方使用
=
,这样一来,看这段代码的人(可能是你未来的自己)可能一开始会把它误认为这样的打字错误,然后再纠正它。最好用一行或两行额外的文字写清楚,不要引起任何混淆。问题-如果正确答案是
0
,为什么
elseif
会是真的?我对此进行了模拟,发现除了运算符优先级不正确(赋值的优先级低于逻辑and)之外,如果答案真的是
0
,那么最终的结果基本上是
elseif(0)
,这不应该是真的!是的,我发现在var&api调用周围添加额外的括号会将api调用的值返回到var中,而不仅仅是将var设置为1或true。非常感谢!是的,我现在正在编写额外的代码行,然后对照var进行检查。
<?php
const AUTH_TYPE_GOOGLE = 1;
function userAuthTypeStub( $x ){
    return 2;
}
if( 0 ){
    // who knows what to do?
}
elseif(
    ( $auth_type = userAuthTypeStub( 0 )  )
    && ( $auth_type != AUTH_TYPE_GOOGLE )
){
    echo "$auth_type\n" . userAuthTypeStub(0) . "\n";
}

2
2