简体   繁体   中英

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?

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM