Dyin
Dyin

Reputation: 5366

PHP empty() strange behaviour

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?

Upvotes: 3

Views: 187

Answers (4)

Andreas Wong
Andreas Wong

Reputation: 60516

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

Upvotes: 3

sthzg
sthzg

Reputation: 5554

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

Upvotes: 2

dan-lee
dan-lee

Reputation: 14492

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.

Upvotes: 2

Crozin
Crozin

Reputation: 44376

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()).

Upvotes: 7

Related Questions