-2

I have two php files. The first one func.php contains a function, and the second one funcTest.php is for testing the function.
First:

<?php
    function func(int $a, int $b, $data) {
          echo "$a, $b, $data";
          return $a + $b;
    }

Second:

<?php
    require_once "PHPUnit/Autoload.php";
    use PHPUnit\Framework\TestCase;
    
    $data = "Some data";

    var_dump($data);
    
    final class funcTest extends PHPUnit_Framework_TestCase {
        public function testFunc() {
            require "func.php";
            $this->assertEquals(3, func(1, 2, $data));
        }
    }

The problem is when I run test using phpunit in cmd, I get these errors:

There was 1 error:

  1. funcTest::testFunc Undefined variable: data

C:\xampp\htdocs\someproject\funcTest.php:12

P.S. I've found similar questions on SO and other forums, but none of those helped me. So please DO NOT CLOSE OR DISS MY QUESTION.

Tofu
  • 199
  • 2
  • 12
Coder4Fun
  • 135
  • 1
  • 14
  • 2
    Have you read through https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and ? – Nigel Ren Feb 02 '21 at 19:51
  • Variable scope is one of the very basics of any programming language. I suggest you thoroughly read the question that Nigel linked, you'll literally need that knowledge everywhere. – El_Vanja Feb 02 '21 at 19:53
  • 1
    The combination of `require_once "PHPUnit/Autoload.php";`, `use PHPUnit\Framework\TestCase;`, and `PHPUnit_Framework_TestCase` makes no sense. You are mixing different versions of PHPUnit. – Sebastian Bergmann Feb 03 '21 at 06:12
  • @NigelRen oh I see. I've tried to write require "func.php" in the global scope of funcTest.php file and now it works! Thank you. – Coder4Fun Feb 03 '21 at 09:35
  • @NigelRen will you write the answer? I'll mark it as the solving of my problem – Coder4Fun Feb 03 '21 at 09:36
  • But why was I dissed? That's wrong to just diss every single question that you don't like, you whoever did this – Coder4Fun Feb 03 '21 at 09:40

1 Answers1

-1

As mentioned by others, its good to read up on variable scoping

$data = "Some data";

var_dump($data);

final class funcTest extends PHPUnit_Framework_TestCase {
    public function testFunc($data) // <---- You need to pass the $data variable into the method
    
    {
        require "func.php";
        $this->assertEquals(3, func(1, 2, $data));
    }
} 

// instantiate and call the method
$test = new funcTest;
$test->testFunc($data); //<--- Pass in the $data variable when calling the method
luke
  • 51
  • 5