3

isset() in php 5.3 seems to be behaving unexpectedly. I have a class called DB details that encapsulates a bunch of string properties with getters and setters.

$dbdetails->getDatabasename() evaluates to a string ("mydb")

This throws a 500 error:

if(!isset($dbdetails->getDatabasename())){
//do something
}

This works fine

$databasename = $dbdetails->getDatabasename();
if(!isset($databasename)){
//do something
}

I wasn't able to see any log output because apache sent back a 500 even though the error ini param is set (sic) to On. I know this is something to do with the isset call for sure. Any idea what could be wrong, or did I find a PHP bug?

Anas
  • 5,622
  • 5
  • 39
  • 71
SR Bhaskar
  • 898
  • 7
  • 17
  • Which error ini param is set to on? `display_errors`? - for some errors your need `error_log` as well. – hakre May 18 '12 at 10:47

2 Answers2

7

The isset function checks whether a variable is set. Checking against $databasename is valid, because it is a variable that can be set or not. Checking against a function is invalid, because it simply isn't a variable.

You probably want to use is_null( $value ) when checking the immediate result of a function.


An example from the comments on the the is_null documentation:

<?php
function test( ) { return null; }
var_dump( is_null( test( ) ) ); // displays "true"
var_dump( isset( test( ) ) ); // parse error, because "test()" is not a variable
?>
soimon
  • 2,400
  • 1
  • 15
  • 16
  • @programmerravi You're welcome :) Don't forget to flag either answer as 'accepted' when you are content. – soimon May 17 '12 at 22:58
4

That's how isset() works. Same as empty(). They can only work with a variable, not an expression. From the documentation:

isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.

Therefore, isset(function_call()) is invalid syntax.

rid
  • 61,078
  • 31
  • 152
  • 193
  • Excellent -- guess this is another one of those 'This ain't Java, noob' things! Thank you – SR Bhaskar May 17 '12 at 22:28
  • The PHP developers actually put out an RFC for exactly this change about a month ago. Although from the looks of it, empty() will be getting this behavior but not isset() https://wiki.php.net/rfc/empty_isset_exprs – flurry May 17 '12 at 22:48