3

以下代码(#1):

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

...将输出:

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

以下代码(#2):

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

...将输出:

没有。没有错误,没有一个字符。没什么。

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

那里发生了什么?

4

4 回答 4

7

empty()不是一个函数,虽然它看起来一个函数。它只是一种仅适用于变量的特殊语法,例如empty($abc). 您根本不能使用诸如empty(123)or之类的表达式empty($obj->getSth())

于 2012-04-21T14:39:27.217 回答
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

于 2012-04-21T14:40:51.650 回答
2

php.net一样

empty() 仅检查变量,因为其他任何内容都会导致解析错误。换句话说,以下内容将不起作用:empty(trim($name))。

这是因为empty()不是函数,而是语言构造,因此仅限于这种行为。

于 2012-04-21T14:40:07.030 回答
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

于 2012-04-21T14:40:17.280 回答