在PHP中使用vs包含 [英] Use vs Include in PHP

查看:80
本文介绍了在PHP中使用vs包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力了解PHP名称空间并使用PHPUnit进行测试.

I'm trying to get my head around PHP namespaces and testing with PHPUnit.

当我在Windows的命令行中运行phpunit test.php时,来自Codewars的这些测试通过:

These tests from Codewars pass when I run phpunit test.php in the command line on Windows:

<?php
require 'solution.php';
use PHPUnit\Framework\TestCase;

class myTests extends TestCase {
  public function testExamples() {
        $this->assertEquals(pair_sum([1,9,2,8,3,7,4,6,5,5,13,14,11,13,-1],10),6);
        $this->assertEquals(pair_sum([1,2,3,1],3),1);
        $this->assertEquals(pair_sum([1,3,2,2],4),2);
        $this->assertEquals(pair_sum([1],4),false);
        $this->assertEquals(pair_sum([2,3,10,-5],5),2);
  }
}

但是,当我注释掉use PHPUnit\Framework\TestCase;时,我得到了Class 'TestCase' not found,这很有意义,因为没有引用所需的类/函数.

However, when I comment out use PHPUnit\Framework\TestCase; I get Class 'TestCase' not found which makes sense since there is no reference to the needed classes/functions.

尽管如此,令我感到困惑的是,关于命名空间的许多答案都声称use关键字不能替代include/require,并且类仍需要包含/自动加载(?).

What's confusing me though is that lots of answers here on SO about namespacing claim that the use keyword is NOT a substitute for include/require and that the classes still need to be included/autoloaded(?).

我在这里没有使用任何自动加载功能-只是一个solution.php文件,上面的测试都在test.php文件中.

I'm not using any autoloading here - just a solution.php file and the tests above in a test.php file.

有人可以解释一下我在这里缺少什么吗?没有任何明确的PHPunit功能,测试如何进行?

Can someone please explain what I'm missing here? How come the tests work without any explicit including of the PHPunit functionality?

我应该提到我已经通过Composer在全球范围内安装了PHPUnit.

I should mention that I have PHPUnit installed globally via Composer.

推荐答案

清除命名空间(在此处忽略类文件的加载)

To make namespaces clear (ignore load of the class file here)

因此在一个php文件中:

So in one php-file:

namespace xyz {
  class a {}
  class b {}
}
namespace abc {
  use xyz\a;
  new a();
  new \xyz\b();
  class b extends a {}
}
namespace {
 use abc\b as aa;
 use xyz\b as bb;
 new bb;
 new aa;
}

命名空间用于防止名称冲突!

Namespace are for preventing name-conflicts!

这篇关于在PHP中使用vs包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆