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?

2
  • Is displaying errors turned on? Commented Apr 21, 2012 at 14:38
  • Yes, they are turned on! Commented Apr 21, 2012 at 14:39

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah. Just stored the return value of getCollection() in a variable before using empty(). PHP is sick.
@Dyin PHP is sick. - I couldn't agree more. ;)
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

2 Comments

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 hmm, also try with ini_set('error_reporting', E_ALL) along with display_errors, see if that helps
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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.