函数惰性加载

Testing Is Documentation

tests/Kernel/FnTest.php函数惰性加载 - 图1

使用函数惰性加载可以更好地管理辅助方法,避免载入过多无用的辅助函数,并且可以提高性能。

func 是一个全局函数随着 kernel 包自动加载,可以在业务中随时使用,组件开发中请使用原生 class_exists 导入函数。

Uses

  1. <?php
  2. use Error;
  3. use Exception;

分组函数

  1. public function testGroup(): void
  2. {
  3. $this->assertFalse(function_exists('Tests\\Kernel\\Fixtures\\Func\\testgroup_fn1'));
  4. $this->assertFalse(function_exists('Tests\\Kernel\\Fixtures\\Func\\testgroup_fn2'));
  5. $result = func(fn () => testgroup_fn1());
  6. $this->assertSame('hello world', $result);
  7. $result = func(fn () => testgroup_fn2());
  8. $this->assertSame('hello world2', $result);
  9. $this->assertTrue(function_exists('Tests\\Kernel\\Fixtures\\Func\\testgroup_fn1'));
  10. $this->assertTrue(function_exists('Tests\\Kernel\\Fixtures\\Func\\testgroup_fn2'));
  11. }

单个函数

  1. public function testSingleFn(): void
  2. {
  3. $this->assertFalse(function_exists('Tests\\Kernel\\Fixtures\\Func\\single_fn'));
  4. $result = func(fn () => single_fn());
  5. $this->assertSame('hello single fn', $result);
  6. $this->assertTrue(function_exists('Tests\\Kernel\\Fixtures\\Func\\single_fn'));
  7. }

目录索引函数

  1. public function testIndex(): void
  2. {
  3. $this->assertFalse(function_exists('Tests\\Kernel\\Fixtures\\Func\\foo_bar'));
  4. $result = func(fn () => foo_bar());
  5. $this->assertSame('foo bar', $result);
  6. $result = func(fn () => foo_bar(' haha'));
  7. $this->assertSame('foo bar haha', $result);
  8. $result = func(fn (string $extend = '') => foo_bar($extend), ' haha');
  9. $result = func(function (string $extend = '') {
  10. return foo_bar($extend);
  11. }, ' haha');
  12. $this->assertSame('foo bar haha', $result);
  13. $this->assertTrue(function_exists('Tests\\Kernel\\Fixtures\\Func\\foo_bar'));
  14. }