Reputation: 1522
Consider these two examples:
// explicitly setting the variable
$file = '/example.php';
if (file_exists($file)) {
include($file);
}
// setting the variable within a function call
if (file_exists($file = '/example.php')) {
include($file);
}
I tested both, and they seem to be working identical.
The second one seems much more concise and less prone to errors, despite having less characters. Yet, I've never seen this being used in practice, and guides will usually advertise the first method.
Are there any reasons against setting variables in this manner? If so, are they exclusively of coding style nature, or is there a technical difference? Are there any other differences I haven't addressed?
Upvotes: 0
Views: 33
Reputation: 230306
If anything, the second one is needlessly confusing. In the example above it's not much of a problem (one can infer enough from the names), but consider this one:
update_user_status($admin = true)
Did the author mean to set $admin
variable like that? Or they simply made a typo and it should be an equality check instead ($admin == true
)?
First style is immune to this.
Upvotes: 1