首页 > 解决方案 > 将特征函数引用存储在数组中

问题描述

trait foo {

 function foo() {
   echo "bar";
 }

}

trait bar {
  use foo;

  function bar() {
   return $this->foo();
  }

}

class global {
  use test;

  public $functions = ["bar"];

  function callFunction($function) {
    call_user_func($this->functions[$function]);
  }

}

不幸的是,这是我能找到的唯一解决方案,除非它触发致命错误响应,否则无法在任何执行变量之前使用 @ 来抑制它。所以,还是有点卡在这里......谁能帮我解决这个问题?我只能使用 ini_set("display_errors", 0) 隐藏致命错误的显示,它仍然允许我显示其他错误类型

How do I store the function bar() as a reference value in $functions without evoking some kind of error such as "call to undefined function bar in globals"?


Ah! Found a solution thanks to zneak here: https://stackoverflow.com/a/16380836/784446 

Essentially, the solution would store both traits and trait functions by array inside a functions array and would then be referenced by combining the elements into a single array, like so:


class global {
 use test;

 public $functions = ["classes"=>["foo", "bar"], "functions"=>["foo", "bar"]];

 function callBar() {
  $traitClass = $this->functions["classes"]["bar"];
  $traitFunction = $this->functions["functions"]["bar"];
  $barTrait = array($traitClass, "$traitFunction");
  $barTrait();
 }
}

特别感谢 zneak 帮助解决这个问题!

标签: php

解决方案


推荐阅读