3

The following code (#1):

var_dump($myObject->getBook()->getCollection());
$testArray=Array();
var_dump($testArray);
var_dump(empty($testArray));

...will output:

array(0) { } array(0) { } bool(true)

The following code (#2):

var_dump($myObject->getBook()->getCollection());
$testArray=Array();
var_dump($testArray);
var_dump(empty($myObject->getBook()->getCollection()));

...will output:

Nothing. No error, not a single character. No nothing.

class Book{
  protected $bidArray=Array();
  public function getCollection(){
    return $this->bidArray;
  }
}

What is happening there?

Dyin
  • 5,815
  • 8
  • 44
  • 69

4 Answers4

7

empty() is not a function, although it looks like a one. It's just a special syntax that works only with variables, e.g. empty($abc). You simply cannot use expressions such as empty(123) or empty($obj->getSth()).

Crozin
  • 43,890
  • 13
  • 88
  • 135
3

You cannot use empty() with anything other than variable (that means no function call as well).

var_dump(empty($myObject->getBook()->getCollection()));

You must have your error display turned off, as the following:

<?php

class Bar {
        function foo() {
        }
}

$B = new Bar();
empty($B->foo());

Gives

PHP Fatal error: Can't use method return value in write context in D:\cw\home\andreas\test\empty.php on line 9

Fatal error: Can't use method return value in write context in D:\cw\home\andreas\test\empty.php on line 9

On my local.

Try doing ini_set('display_errors', true) prior to your var_dump's and see if the error messages crop up

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
  • Tired to set `display_errors` as you mentioned. Still no output. Got fatal errors from elsewhere BTW. Using PHP 5.3.8 with XAMPP. – Dyin Apr 21 '12 at 14:46
  • @Dyin hmm, also try with `ini_set('error_reporting', E_ALL)` along with `display_errors`, see if that helps – Andreas Wong Apr 21 '12 at 14:47
2

As on php.net

empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).

This is because empty() isn't a function, but a language construct and therefore limited to this behaviour.

dan-lee
  • 14,365
  • 5
  • 52
  • 77
2

Using empty() you can't check directly against the return value of a method. More info here: Can't use method return value in write context

Community
  • 1
  • 1
sthzg
  • 5,514
  • 2
  • 29
  • 50