【问题标题】:Trigger method/script when using "use" keyword使用 \"use\" 关键字时触发方法/脚本
【发布时间】:2023-02-21 00:23:57
【问题描述】:

当在 php/laravel 中使用 use 关键字时,有没有办法执行方法/脚本?

我有一个班级和一个特质

每当在类中使用时,我都想在特征中执行一个方法(仅一次) 我认为在 trait 的构造函数中这样做是可行的,而且确实如此,直到我遇到一个只有静态方法的类。

例如:

class A {
   use B;
   public static function hello() {
      return "hello";
   }
}

trait B {
   function i_want_to_execute_on_use_keyword_but_just_once() {
      return "Executing important things";
   }
}

A::hello(); ---\> B's method should execute before this\`

php/laravel 中有什么东西可以让我执行这种行为吗?

注意:在我的实际场景中,我需要对使用特征的类运行反射。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您将需要实例化类以从静态方法访问其方法,甚至来自特征。 Obs:我公开了该方法以作为方法访问。

    class A {
       use B;
       public static function hello() {
          $static = new static();
          $static->i_want_to_execute_on_use_keyword_but_just_once();
          return "hello";
       }
    }
    
    trait B {
       public function i_want_to_execute_on_use_keyword_but_just_once() {
          return "Executing important things";
       }
    }
    

    所有 Traits 方法/函数都可以通过 $this 访问(尊重 OO 层次结构)。

    我不知道你的情况/应用程序的上下文,但我相信有更好的方法来处理这种情况,作为服务类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 2013-09-02
      • 2017-07-23
      • 2016-10-11
      • 1970-01-01
      相关资源
      最近更新 更多