Search code examples
phpphpunitphp-7

Cannot access the properties inside the Closure object in php 7


I have this in my unit test code:

$data = $this->_createSfApiFindMock($cisDataCount);
var_dump($data()); die();

output:

class Closure#731 (3) {
  public $static =>
  array(4) {
    'cisDataCount' =>
    int(201)
    'cisBillObjectBase' =>
    class stdClass#716 (20) {
      public $unisrv_dcis__TargetMonth__c =>
      string(6) "202301"
      .........
      public $unisrv_dcis__Member__r =>
      class stdClass#717 (1) {
        ...
      }
      public $unisrv_dcis__Contract__r =>
      class stdClass#718 (3) {
        ...
      }
    }
    'cisBillDetailsObjectBase' =>
    array(5) {
      [0] =>
      class stdClass#720 (11) {
        ...
      }
      [1] =>
      class stdClass#722 (11) {
        ...
      }
      [2] =>
      class stdClass#724 (11) {
        ...
      }
      [3] =>
      class stdClass#726 (11) {
        ...
      }
      [4] =>
      class stdClass#728 (13) {
        ...
      }
    }
    'maxDataChunkSize' =>
    int(200)
  }
}

How to get access to cisBillDetailsObjectBase?

I tried:

$cisBillDetailsObjectBase = $data->static['cisBillDetailsObjectBase'];
$data->static();
$data->static;
$data->{"\0Closure\0static"};

Solution

  • You cannot access to the content of a Closure. A Closure is a function to execute.

    Take a look to this simple code:

    var_dump(function() { static $a; });
    

    Output

    object(Closure)#1 (1) {
      ["static"]=>
      array(1) {
        ["a"]=>
        NULL
      }
    }
    

    You cannot access to the internal data of the function because of the scope.

    You should execute the closure that return something or interact with something else to "export" its data.

    Example:

    $a = function() { static $a = 2; return $a; };
    var_dump($a()); // CALL
    

    Output:

    int(2)