Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is declaring a variable inside of calling a method bad practice?

Tags:

php

If I was to call a method which took a parameter, and then defined a variable at the same time, would that be considered "bad practice"?

Example:

if( file_exists( $file = "skins/Default/Controllers/Demo.php" ) )
{
    require( $file );
}

I feel as though it makes things easier as it doesn't require creating another variable above, nor does it clutter the code up by writing the string twice.

like image 284
Jarrod Avatar asked Mar 13 '23 02:03

Jarrod


1 Answers

Is declaring a variable inside of calling a method bad practice?

Yes, because it hides the intent behind other functionality.

$file = "skins/Default/Controllers/Demo.php";
if (file_exists($file)) {
    require($file);
}

is easier to read and reason about than:

if (file_exists($file = "skins/Default/Controllers/Demo.php")) {
    require($file);
}

because it'd be easily mistaken for $file == "skins/Default/Controllers/Demo.php", which is common to see within an if statement.

like image 88
zzzzBov Avatar answered Mar 16 '23 03:03

zzzzBov