Skip to content

once exercise HELP!! #1

Open
Open
@jbigorra

Description

@jbigorra

Hi @danrevah , I was wondering if you could help me with this exercise. I haven't been able to figure out how to not share the same scope for the $n variable when the two calls $init1 = once($value); and $init2 = once($value) are done in testMultiUse().

This is what've got so far:

<?php

function once($func)
{
  $result;
  return function () use ($func) {
    static $n = 2;
    global $result;

    $arg = func_get_args()[0];
    $n--;
    if ($n > 0) {
      $args = func_get_args();
      $nArgs = func_num_args();
      if ($nArgs === 1) $result = call_user_func_array($func, $args);
      elseif ($nArgs > 1) $result = call_user_func($func, ...$args);
    }
    return $result;
  };
}

You think you can give me a hand to finish it completely?
Thanks!

Edit:

Almost there:

PHPUnit 5.7.27 by Sebastian Bergmann and contributors.

...F                                                                4 / 4 (100%)

Time: 5.11 seconds, Memory: 4.00MB

There was 1 failure:

1) OnceTest::testMultiUse
Failed asserting that 1 matches expected 2.

/home/jbigorra/Projects/php-exercises/once/test.php:63

FAILURES!
Tests: 4, Assertions: 13, Failures: 1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions