I came across this question which features the following code piece:
<?php
class Goat{
public $goat_id;
public $goat_name;
public $hashed_password;
....
public static function authenticate($username, $password){
$is_auth; // This line
if(!empty($result)){
$user = array_shift($result);
$is_auth = Pass_auth::verify_password($password, $user- >hashed_password);
}
if($is_auth) {
return $user;
}
....
}
}
My question comes from the marked line inside the authenticate function. Not specifically to this example -but in general- what is the point of this $is_auth;
declaration, just sitting there doing nothing?
I have obviously tried to find an answer before posting here but if this layout/behaviour has a specific name I don't know it.
I have made some sandbox variations and am surprised to find that none of them produce any errors, the below code is error free:
<?php
error_reporting(E_ALL);
$small = "tree";
//$small = false; //swapping var value types makes no difference.
$small;
$sdgdfghdgd;
$is_auth;
is a perfectly valid PHP expression. It's value is the value of $is_auth
and it doesn't have any effect.
The PHP compiler is smart enough to detect that the expression is useless (because it's value is not used and it doesn't have any side effect) and it doesn't generate any opcode for it.
If it were generating any code, that code should trigger an E_NOTICE
because the variable is not defined yet.
The situation changes when the expression involves an array. Even if, conceptually, the expression $a['foo'];
is equivalent with $is_auth;
, $a['foo'];
is not optimized out by the compiler. It is evaluated and it triggers the expected E_NOTICE
when $a
is not defined or it doesn't have the key 'foo'
.