Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Fatal error: Cannot use $this as parameter

I've the following PHP method which is part of the codebase which was working fine:

<?php
class HooksTest extends DrupalTestCase {
  public function testPageAlterIsLoggedIn() {
    $this->drupal->shouldReceive('userIsLoggedIn')
      ->once()
      ->andReturn(TRUE);
    $this->drupal->shouldReceive('drupalPageIsCacheable')
      ->once()
      ->andReturnUsing(function ($this) {
        return $this;
      });
    $page = [];
    $cacheable = $this->object->pageAlter($page);
    $this->assertFalse($cacheable);
  }
}

The code was passing all the CI tests before (using phpunit).

However now when I'm invoking the file via php HooksTest.php, I've got the following error:

PHP Fatal error: Cannot use $this as parameter in HooksTest.php on line 11

Fatal error: Cannot use $this as parameter in HooksTest.php on line 11

I've tested with PHP 7.1, 7.2 and same issue. I believe it was working in PHP 5.6.

How can I convert above code to have the same meaning?

Does removing $this from the function parameter should be enough?

like image 941
kenorb Avatar asked Dec 24 '22 14:12

kenorb


1 Answers

Just skip $this argument, change

function ($this) {
    return $this;
}

to

function () {
    return $this;
}

Look at Example #5 Automatic binding of $this on Anonymous functions page:

<?php
class Test
{
    public function testing()
    {
        return function() {
            var_dump($this);
        };
    }
}
$object = new Test;
$function = $object->testing();
$function();
?>
like image 84
ponury-kostek Avatar answered Jan 10 '23 09:01

ponury-kostek